1

This code will not compile:

        var x = new {
            Property = null,
        };

With following exception: Cannot assign null to anonymous type property

But this will work fine:

        var someBool = false;
        var x = new {
            Property = someBool ? "value" : null,
        };

I think there is implicit casting something like this - (string)null but not exactly sure.

So I would like to know more about this case and how this works internally (I didn't find any article explaining this)

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
Cseed rvr
  • 19
  • 3

1 Answers1

5

Compiler needs to determine type for anonymous type's properties which can't be done from just null (though you can argue about using object in this case but see the following quote), on the contrary ternary operator has a type (see the linked docs explaining how compiler determines it), which is string in case of someBool ? "value" : null.

From anonymous types doc:

The expression that is used to initialize a property cannot be null, an anonymous function, or a pointer type.

Guru Stron
  • 102,774
  • 10
  • 95
  • 132