Consider the following two programs. The first program fails at compile time with a compiler error:
using System.Collections.Generic;
class Program {
static void Main(string[] args) {
List<int> bar = { 0, 1, 2, 3 }; //CS0622
}
}
Can only use array initializer expressions to assign to array types. Try using a new expression instead.
This I fully understand. Of course, the remedy is to use the new[] {...}
array initializer syntax, and the program will compile and run properly.
Now consider a second program, only slightly different:
using System.Collections.Generic;
public class Foo {
public IList<int> Bar { get; set; }
}
class Program {
static void Main(string[] args) {
Foo f = new Foo { Bar = { 0, 1, 2, 3 } }; //Fails at run time
}
}
This program compiles. And what's more, the run-time error generated is:
Object reference not set to an instance of an object.
This is interesting to me. Why would the second program even compile? I even tried making Bar
an instance variable instead of a property, thinking that might have something to do with the odd behavior. It does not. As in the first example, using the new[] {...}
array initializer syntax causes the program to run properly with no errors.
It would seem to me that the second program should not compile. Here's the question. Why does it? What is it I'm failing to grasp here?
(Compiler: Visual Studio 2012, Framework: .NET 4.5.1)