When I run this code, it doesn't initialize ThisIsAList
to an empty collection as I was expecting... instead ThisIsAList
was null.
void Main()
{
var thing = new Thing
{
ThisIsAList = {}
};
Console.WriteLine(thing.ThisIsAList == null); // prints "True"
}
public class Thing
{
public List<string> ThisIsAList { get; set; }
}
Why isn't this a compile error? Why is the result null
?
I was wondering if maybe there was an implicit conversion going on here, but the following attempts produced compile errors:
thing.ThisIsAList = Enumerable.Empty<string>().ToArray();
List<int> integers = { 0, 1, 2, 3 };
According to MSDN documenation on collection initializers, it sounds like a collection initializer basically just handles calling Add()
for you. So
I looked for possible overloads to List.Add
, but didn't find anything that I think would apply.
Can someone explain what's going on here from the C# spec?