Csupor Jenő Csupor Jenő - 1 month ago 6
C# Question

Null Exception on List<T> initialization

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;
}

Answer

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.

Comments