47

I have the following in WebAPI that is converted to a JSON string and sent to the client:

return Ok(new
    {
        Answer = "xxx",
        Text = question.Text,
        Answers = question.Answers.Select((a, i) => new
        {
            AnswerId = a.AnswerId,
            AnswerUId = i + 1,
            Text = a.Text
        })
    });

Now I realize that I would like to assign the value null to Answer. However this gives me a message saying

cannot assign <null> to anonymous type property. 

Is there a way I can do this without having to define a class just so I can assign the null?

Alan2
  • 23,493
  • 79
  • 256
  • 450
  • 2
    I don't think this is a duplicate. This is useful, specific question with a simple answer. The linked question covers it, but is about dealing with an array. – goodeye Dec 20 '19 at 17:28

1 Answers1

110

Absolutely - you just need to cast the null value to the right type so that the compiler knows which type you want for that property. For example:

return Ok(new {
    Answer = (string) null,
    Text = ...,
    ...
});
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Is (string) null really different from (int) null ? – Anshul May 09 '17 at 00:23
  • 3
    @Anshul: Well `(int) null` isn't valid... but if you picked a type that *was* valid, then yes, they're different as they have different compile-time types, which means the anonymous types in the result would have different property types. – Jon Skeet May 09 '17 at 05:54
  • 1
    "Well (int) null isn't valid" -- Not sure why I didn't realize that. Of course. Thanks for your answer. Makes sense. – Anshul May 09 '17 at 16:45
  • Great! Remembering that for some primitive and boolean types, the null value is not allowed. – Wedson Quintanilha da Silva Nov 05 '20 at 18:53
  • 1
    it should be (string?)null now – Timur Lemeshko Apr 28 '23 at 14:29
  • @TimurLemeshko: That depends on whether you're in a nullable context or not. I'm *definitely* not going to go back over thousands of code answers to make changes which could just as easily break some users. – Jon Skeet Apr 28 '23 at 14:54