Null Exception on List<t> initialization

时间:2016-10-20 13:10:02

标签: c#

Why does the following code compile, but throw a NullReferenceException?

using System.Collections.Generic;

class Program
{
    static void Main()
    {
        C c = new C { P = { "" } };
    }
}

class C
{
    public List<string> P;
}

2 个答案:

答案 0 :(得分:1)

Basically the code

C c = new C { P = { "" } };

is really short hand for

C temp = new C();
temp.P.Add("");
C c = temp;

So it's not creating the list, just trying to add to it and thus the run time error, but no compilation error.

答案 1 :(得分:0)

The reason it complies is because

C c = new C { P = { "" } };

is valid C#.

It only checks to see if P is not null at run-time - hence the runtime NullReferenceException.