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?
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
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";
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