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)

3
  • 2
    Really? stackoverflow.com/questions/24851913/… Commented Dec 8, 2022 at 19:19
  • My main question is how this works internally Commented Dec 8, 2022 at 19:22
  • 1
    So read the answer carefully: "so that the compiler knows which type you want for that property". Commented Dec 8, 2022 at 19:23

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

string? actually.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.