Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a new value to an anonymous type

Tags:

json

c#

is it possible to add a value to existing json object?

My example code:

var obj = new { Vall = "myVal1", Val2 = "myVal2", Val3 = "myVal3" };

this is what I'm trying to do:

obj.AddValue(Val4, "myVal4");
like image 766
SteinTheRuler Avatar asked Oct 19 '25 14:10

SteinTheRuler


1 Answers

var obj = new { Vall = "myVal1", Val2 = "myVal2", Val3 = "myVal3" };

is not JSON, despite the similarity. That is a compiler-generated "anonymous type", which means the compiler creates a type for you with three string properties named Val1, Val and Val3. Other than the fact that you can't speak the name of the type (it is anonymous), it is a pretty normal .NET class. No, you can't add extra properties to a class at runtime.

The closest thing to what you want might be ExpandoObject, but to be honest it sounds like you're trying to do something peculiar.

like image 178
Marc Gravell Avatar answered Oct 21 '25 03:10

Marc Gravell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!