Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does C# allow to assign anonymous object to class fields which are of class types?

Tags:

c#

.net

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.

like image 624
Hoang Hiep Avatar asked Nov 26 '25 14:11

Hoang Hiep


2 Answers

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
    };
}
like image 122
Matt Rowland Avatar answered Nov 28 '25 03:11

Matt Rowland


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.

like image 44
David Pine Avatar answered Nov 28 '25 02:11

David Pine



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!