Consider the following:
public class Foo
{
public List<int> ListProp { get; set; } = new List<int>();
public int[] ArrayProp { get; set; } = new int[3];
}
public static void Main()
{
new Foo
{
// This works, but does not call the setter for ListProp.
ListProp = { 1, 2, 3 },
// This gives a compiler error: 'int[]' does not contain a
// definition for 'Add' and no extension method 'Add' accepting
// a first argument of type 'int[]' could be found (are you
// missing a using directive or an assembly reference?)
ArrayProp = { 4, 5, 6 }
};
}
I am curious to understand what's going on. The ListProp setter doesn't get called. And the compiler error where we try to assign ArrayProp suggests that internally, this assignment will try to call an "Add" method.
PS: Obviously, the code can be made to work thus: ArrayProp = new int[] { 4, 5, 6 }
but that doesn't satisfy my curiosity :)
Because it isn't actually being re-set. The collection initializer syntax sugar will actually call
List<T>.Add
in this case. It's basically doing:That's right, as mentioned above, the collection initializer is no more than syntax sugar for calling the
Add
method on the given collection. Sinceint[]
, or any array for that matter doesn't posses anAdd
method, you get a compile time error.