Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is happening with this C# object initializer code?

Tags:

c#

What is going on with this C# code? I'm not even sure why it compiles. Specifically, what's going on where it's setting Class1Prop attempting to use the object initializer syntax? It seems like invalid syntax but it compiles and produces a null reference error at runtime.

void Main()
{    
    var foo = new Class1
    {
        Class1Prop = 
        {
            Class2Prop = "one"
        }
    };
}

public class Class1
{
    public Class2 Class1Prop { get; set; }
}

public class Class2
{
    public string Class2Prop { get; set; }
}
like image 237
Jack Dolabany Avatar asked Oct 24 '18 20:10

Jack Dolabany


1 Answers

This is allowed by object initializer syntax in the C# specification, where it is called a nested object initializer. It is equivalent to:

var _foo = new Class1();
_foo.Class1Prop.Class2Prop = "one"
var foo = _foo;

It should be a little more obvious why this throws a null reference exception. Class1Prop was never initialized in the constructor of Class1.

The benefit of this syntax is that the caller can use the convenient object initializer syntax even when the properties are getter-only to set mutable properties on nested objects. For example, if Class1Prop was a getter-only property the example is still valid.

Note that there is an inaccessible temporary variable created to prevent the access of a field or array slot before the full initialization has run.

like image 186
Mike Zboray Avatar answered Nov 16 '22 06:11

Mike Zboray