NRE when using an array initializer in an object initializer

I am observing some strange behavior (tested in VS2013) when using an array initializer in the following case:

    class A
    {
        public List<int> Items { get; set; }
    }

    void Main(string[] args)
    {
        // (1) it compiles, but failing with NRE in runtime
        var a = new A { Items = { 1, 2, 3 } };

        // (2) it does not compile, as expected
        List<int> b = { 1, 2, 3 };
    }

Actually, I would expect a compiler error in case (1), the same thing as mine in case (2): Can only use array initializer expressions to assign to array types. Try using a new expression instead.But case (1) compiles without any problems and the expected crash NullReferenceExceptionon startup, Can anyone explain why the compiler resolves case (1)?

+4
source share
1 answer

Here is a reference quote from the C # specification (version 5, section 7.6.10.2):

, , . , , , . , , 7.6.10.3.

, , , :

var a = new A { Items = { 1, 2, 3 } };

- ( , IL):

var a = new A();
a.Items.Add(1);
a.Items.Add(2);
a.Items.Add(3);

, , NullReferenceException, Items null.

, A:

class A
{
    public List<int> Items { get; set; }
    public A() { Items = new List<int>(); }
}
+1

Source: https://habr.com/ru/post/1589287/


All Articles