Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I assign a null value to an anonymous type property? [duplicate]

Tags:

c#

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?

like image 338
Alan2 Avatar asked Jul 20 '14 15:07

Alan2


People also ask

Can we assign list as null?

Yes, We can insert null values to a list easily using its add() method. In case of List implementation does not support null then it will throw NullPointerException.

Can we create nested anonymous type?

You are not allowed to create a field, property, event, or return type of a method is of anonymous type. You are not allowed to declare formal parameters of a method, property, constructor, indexer as a anonymous type. The scope of the anonymous type is always limited to the method in which they are defined.


1 Answers

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 = ...,     ... }); 
like image 154
Jon Skeet Avatar answered Sep 19 '22 15:09

Jon Skeet