Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this C# assignment throw an exception?

Tags:

c#

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.

like image 669
Otávio Décio Avatar asked Jun 29 '11 19:06

Otávio Décio


1 Answers

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";
like image 189
Jon Avatar answered Oct 18 '22 19:10

Jon