Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 515
Matt Jenkins Avatar asked May 14 '26 20:05

Matt Jenkins


1 Answers

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.

like image 53
Yuval Itzchakov Avatar answered May 16 '26 10:05

Yuval Itzchakov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!