Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected behavior with object initializer [duplicate]

Tags:

c#

Not exactly sure how this is working. Not even sure how I can even use object initializer while building the Child class. And then how its overriding my default Test class.

internal class Program
{
    static void Main(string[] args)
    {
        Child child = new Child
        {
            Test = { Name = "hello" }
        };

        //child.Test.Name prints out "hello"
    }
}

public class Child : Parent
{
    public Child()
    {
    }
}

public abstract class Parent
{
    public Test Test { get; }

    protected Parent()
    {
        Test = new Test { Name = "Default" };
    }
}

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

Expected an error can't I shouldn't be able to use object initializer on Test and the default can't be changed.

like image 401
Enei4Life Avatar asked Jul 10 '26 02:07

Enei4Life


2 Answers

You are thinking of

Test = new Test { Name = "hello" }

which is indeed not allowed because Test does not have a setter.

On the other hand,

Test = { Name = "hello" }

is totally fine because it doesn't set Test. It just sets Test.Name, and Name indeed has a setter.

From the spec,

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 65
Sweeper Avatar answered Jul 20 '26 07:07

Sweeper


This is akin to:

Child child = new Child();
child.Test.Name = "hello";

Nothing illegal about that.

It is arguably a little unclear when it (the access on Test) is an assignment via set versus a mutate via the get, but one big clue here is the lack of a new; just using = {...} goes via the get.

like image 28
Marc Gravell Avatar answered Jul 20 '26 07:07

Marc Gravell



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!