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?
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.
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