public class A
{
private string _a_string;
public string AString
{
get { return _a_string; }
set { _a_string = value; }
}
}
public class B
{
private string _b_string;
private A _a;
public A A
{
get { return _a; }
set { _a = value; }
}
public string BString
{
get { return _b_string; }
set { _b_string = value; }
}
}
This does not work:
B _b = new B { A = { AString = "aString" }, BString = "bString" };
System.NullReferenceException : Object reference not set to an instance of an object.
This works:
B _b = new B { A = new A { AString = "aString" }, BString = "bString" };
Both compile fine in VS2010.
The line
B _b = new B { A = { AString = "aString" }, BString = "bString" };
is equivalent to
B _b = new B();
_b.A.AString = "aString"; // null reference here: _b.A == null
_b.BString = "bString";
I think in this form it's clear what's happening.
Compare this with the equivalent form of the expression that works:
B _b = new B();
_b.A = new A();
_b.A.AString = "aString"; // just fine now
_b.BString = "bString";
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