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.
There is no instantiation of A within B unless you explicitly instantiate it as in your second example.
Change to;
To use the first example.
In short, without the new A(), there is no A which is the cause of the NullReferenceException