Example:
class Foo
{
public Bar Bar { get; set; }
}
class Bar
{
public string Name { get; set; }
}
...
{
var foo = new Foo
{
Bar = { Name = "abc" } // run-time error
};
}
Why does C# allow that kind of assignment? IMO, it makes no sense but easier to cause bugs.
This is made possible because it would not cause a run-time error if the object had already been instantiated.
class Foo
{
public Bar Bar { get; set; } = new Bar();
}
{
var foo = new Foo
{
Bar = { Name = "abc" } // no error
};
}
This is actually not an anonymous object, but rather the use of object initializer syntax.
{
var foo = new Foo
{
Bar = { Name = "abc" } // run-time error
};
}
The above snippet is actually the same as saying the following:
{
var foo = new Foo();
foo.Bar = new Bar { Name = "abc" }; // Fine, obviouslly
foo.Bar = { Name = "abc" }; // compile error
}
The object name becomes redundant as it is already known with the use of the object initializer syntax.
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