5

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)

Dave Markle
  • 95,573
  • 20
  • 147
  • 170
  • Thanks. I'd searched for that, but wasn't able to find the answer. Figured I had a 75% chance of someone else finding this. – Dave Markle Jun 03 '14 at 17:01
  • 2
    I was pretty surprised to find this already answered as well, but it actually popped up in the "Related" section of this question. Stack Overflow may have just become sentient. – Matt Burland Jun 03 '14 at 17:02
  • 2
    "On June 3, 2014, Stack Overflow became self-aware. In da confusion dey try to pool da plug" – Dave Markle Jun 03 '14 at 17:03

0 Answers0