Setting null values in anonymous object initializer in C#

The spec claims you can’t do this:

It is a compile-time error for an expression in an anonymous object initializer to be of the null type.

And you can’t. Directly.

var obj = new {
  Value = null //syntax error: "cannot assign null to anonymous type property"
};

var obj = new {
  Value = (object)null //full of win
};

//seriously, it works
Console.WriteLine(obj.Value == null); //True

Somebody please explain to me why this works.

February 5, 2010   Posted in: c#

2 Responses

  1. Asaph - February 5, 2010

    I suggest asking this question on http://stackoverflow.com/ . You’ll almost certainly get your answer there.

  2. Mike Valenty - February 14, 2010

    The compiler needs to be able to infer the type of Value, which it can’t do in your first example.

Leave a Reply