C# .NET how null is casting in anonymous type?

137 views Asked by At

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)

1

There are 1 answers

1
Guru Stron On

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.