so, object initializers are all kinds of handy - especially if you're doing linq, where they're downright necessary - but I can't quite figure out this one:
public class Class1 {
public Class2 instance;
}
public class Class2 {
public Class1 parent;
}
using like this:
Class1 class1 = new Class1();
class1.instance = new Class2();
class1.parent = class1;
as an initializer:
Class1 class1 = new Class1() {
instance = new Class2() {
parent = class1
}
};
this doesn't work, class1 is supposedly an unassigned local variable. it gets even trickier in Linq when you are doing something like
select new Class1() { ...
it doesn't even have a name to refer to it by!
how do I get around this? can I simply not make nested references using object initializers?
can I simply not make nested references using object initializers?
You are right - you cannot. There would be a cycle; A requires B for initialization but B requires A before. To be precise - you can of course make nested object initializers but not with circular dependencies.
But you can - and I would suggest you should if possible - work this around as follows.
public class A
{
public B Child
{
get { return this.child; }
set
{
if (this.child != value)
{
this.child = value;
this.child.Parent = this;
}
}
}
private B child = null;
}
public class B
{
public A Parent
{
get { return this.parent; }
set
{
if (this.parent != value)
{
this.parent = value;
this.parent.Child = this;
}
}
}
private A parent = null;
}
Building the relation inside the property has the benifit that you cannot get an inconsitent state if you forget one of the initialization statements. It is quite obvious that this is an suboptimal solution because you need two statements to get one thing done.
b.Parent = a;
a.Child = b;
With the logic in the properties you get the thing done with only one statement.
a.Child = b;
Or the other way round.
b.Parent = a;
And finally with object initializer syntax.
A a = new A { Child = new B() };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With