Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a bug in the C# 4.0 compiler?

This code compiles successfully, but I think it should fail to compile. Also, when you run it you get a NullReferenceException. The missing code is the "new Bar" in the initialization of the Bar property.

class Bar
{
    public string Name { get; set; }
}

class Foo
{
    public Bar Bar { get; set; }
}


class Program
{
    static void Main(string[] args)
    {
        var foo = new Foo
                      {
                          Bar = { Name = "Hello" }
                      };
    }
}

Is this a known bug?

like image 918
Edmondo Pentangelo Avatar asked Oct 01 '10 14:10

Edmondo Pentangelo


2 Answers

Why do you think it should fail to compile? It is nested object initializer syntax, and it is the responsibility of the client code to provide a valid value for initialization.

From the documentation:

C# spec 7.5.10.2 "Object initializers"

A member initializer that specifies an object initializer after the equals sign is a nested object initializer, i.e. an initialization of an embedded object. Instead of assigning a new value to the field or property, the assignments in the nested object initializer are treated as assignments to members of the field or property

like image 125
desco Avatar answered Nov 15 '22 04:11

desco


No this is not a bug.

If you want it to run you either put a new before Bar (just like you did for Foo before the initializer) or you create the Bar object in Foo's constructor.

The object initializer is essentially just syntactic sugar.

This:

var foo = new Foo
            {
                Bar = { Name = "Hello" }
            };

Is exactly the same as this:

var foo = new Foo();
foo.Bar.Name = "Hello"; 
like image 36
Isak Savo Avatar answered Nov 15 '22 03:11

Isak Savo