I have a problem of understanding how is it better to share references between objects.
Sorry for bad example, but I really don't understand how to demonstrate it better.
public class Program
{
static void Main(string[] args)
{
var test1 = new TestProgram1();
test1.DoSomething();
}
}
public class TestProgram1
{
public string Name { get; set; } = "TESTING NAME";
public void DoSomething()
{
var test2 = new TestProgram2();
test2.DoSomething();
}
}
public class TestProgram2
{
public void DoSomething()
{
var test3 = new TestProgram3();
test3.DoSomething();
}
}
public class TestProgram3
{
public void DoSomething()
{
var test4 = new TestProgram4();
test4.DoSomething();
}
}
public class TestProgram4
{
public void DoSomething()
{
var test5 = new TestProgram5();
test5.DoFinal();
}
}
public class TestProgram5
{
public void DoFinal(TestProgram1 testProgram1)
{
Console.WriteLine(testProgram1.Name);
}
}
As you understand, code will newer compile. Because,
public class TestProgram5
{
public void DoFinal(TestProgram1 testProgram1)
{
Console.WriteLine(testProgram1.Name);
}
}
TestProgram5 needs a reference to TestProgram1
This is my question: is there really no other options then, only to send reference to TestProgram1 through all children objects until TestProgram5 through constructor?
Example:
public class Program
{
static void Main(string[] args)
{
var test1 = new TestProgram1();
test1.DoSomething();
}
}
public class TestProgram1
{
public string Name { get; set; } = "TESTING NAME";
public void DoSomething()
{
var test2 = new TestProgram2(this);
test2.DoSomething();
}
}
public class TestProgram2
{
private TestProgram1 TestProgram1 { get; }
public TestProgram2(TestProgram1 testProgram1)
{
TestProgram1 = testProgram1;
}
public void DoSomething()
{
var test3 = new TestProgram3(TestProgram1);
test3.DoSomething();
}
}
public class TestProgram3
{
private TestProgram1 TestProgram1 { get; }
public TestProgram3(TestProgram1 testProgram1)
{
TestProgram1 = testProgram1;
}
public void DoSomething()
{
var test4 = new TestProgram4(TestProgram1);
test4.DoSomething();
}
}
public class TestProgram4
{
private TestProgram1 TestProgram1 { get; }
public TestProgram4(TestProgram1 testProgram1)
{
TestProgram1 = testProgram1;
}
public void DoSomething()
{
var test5 = new TestProgram5();
test5.DoFinal(TestProgram1);
}
}
public class TestProgram5
{
public void DoFinal(TestProgram1 testProgram1)
{
Console.WriteLine(testProgram1.Name);
}
}
I understand that this is a very and very bad example, but it happens when in the process of codding, you realize that in deep children classes, you need a reference to some first parent.
Maybe there is another, better solution for this?