HimBromBeere HimBromBeere - 1 year ago 69
C# Question

initialize collection-member on a class

I have a class with that has a collection-property:

class MyClass
public MyCollection Coll { get; private set; }
public MyClass() { this.Coll = new MyCollection(); }

class MyCollection : IList { ... }

Now I´m creating two different instances of my class:

var o1 = new MyClass() { Coll = {"1", "2"}};
var o2 = new MyClass() { Coll = new MyCollection() {"1", "2"} };

I understand that compiler complains about the latter as the setter for the property doesn´t exist (or in this case isn´t publicly accessable). The first however is an assignement as well - albeit a collection initializer.

I assume that collection-initializers are allowed for get-only properties as they´re just calling
and do not actually call the getter of the property. Is this right?

Answer Source

From your question:

I assume that collection initializers are [...] just calling Add on IList [...].

This assumption is correct. Collection initializers are syntactic sugar that the C# compiler translates into something more explicit during compilation. For instance, the following line:

var l = new List<int>() { 1, 2 };

Is actually translated to:

var l = new List<int>();

You can verify this be looking at the generated MSIL (simplified):

newobj      List<System.Int32>..ctor // Create list object.
stloc.0                              // Store list object as local variable "0".
ldloc.0                              // Push local variable "0" onto the stack.
ldc.i4.1                             // Push 4-byte integer constant "1" onto the stack.
callvirt    List<System.Int32>.Add   // Call "Add" (uses and pops the last two values from
                                     // the stack).
ldloc.0                              // Push list onto stack again.
ldc.i4.2                             // Push constant "2" onto stack.
callvirt    List<System.Int32>.Add   // Call "Add" again.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download