Reputation: 2412
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.
Upvotes: 3
Views: 190
Reputation: 24535
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.
Upvotes: 4
Reputation: 4595
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
};
}
Upvotes: 7