Matt Jenkins
Matt Jenkins

Reputation: 3081

Using an implicitly-typed array in class initializer

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 :)

Upvotes: 3

Views: 105

Answers (1)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149538

The ListProp setter doesn't get called

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:

public static void Main()
{
    Foo expr_05 = new Foo();
    expr_05.ListProp.Add(1);
    expr_05.ListProp.Add(2);
    expr_05.ListProp.Add(3);
}

And the compiler error where we try to assign ArrayProp suggests that internally, this assignment will try to call an "Add" method.

That's right, as mentioned above, the collection initializer is no more than syntax sugar for calling the Add method on the given collection. Since int[], or any array for that matter doesn't posses an Add method, you get a compile time error.

Upvotes: 1

Related Questions