Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does an inline list override a property with no setter?

Tags:

c#

I have an Item class that has a publicly accessible member NoSetter that does not contain a setter. The object does explicitly state a get, which retrieves a private readonly List object.

class Item
{
    private readonly List<string> emptyString;

    public Item()
    {
        this.emptyString = new List<string>();
    }

    public List<string> NoSetter
    {
        get { return this.emptyString; }
    }
}

When you create this object, you can't set NoSetter to a list, the compiler fails whenever you try.

List<string> goldenString = new List<string>();
goldenString.Add("Nope");
Item item = new Item()
{
    NoSetter = goldenString
    // or NoSetter = new List<string>();
};

However if you create the list inline you're able to set NoSetter.

Item item = new Item()
{
    NoSetter = { "But this still works" }
};

// Outputs: "But this still works"
Console.WriteLine(item.NoSetter.First<string>());

I expect that the NoSetter.Get method should be returning the readonly list emptyString , but instead returns the inlined NoSetter object. What causes this in .net? Is it expected?

like image 218
Joshua Avatar asked Jun 11 '15 13:06

Joshua


1 Answers

Your second piece of code isn't setting a new List<string>, it's just adding that value to it.

Item item = new Item()
{
    NoSetter = { "But this still works" }
};

Is equivalent to:

Item item = new Item();
item.NoSetter.Add("But this still works");

The {...} syntax when applied to a collection is known as a Collection Initializer. Quoting from the documentation (emphasis mine):

Collection initializers let you specify one or more element initializers when you initialize a collection class that implements IEnumerable. The element initializers can be a simple value, an expression or an object initializer. By using a collection initializer you do not have to specify multiple calls to the Add method of the class in your source code; the compiler adds the calls.

like image 152
Charles Mager Avatar answered Oct 16 '22 13:10

Charles Mager