Creating an anonymous type dynamically?
42,246
Solution 1
Only ExpandoObject
can have dynamic properties.
Edit: Here is an example of Expand Object usage (from its MSDN description):
dynamic sampleObject = new ExpandoObject();
sampleObject.TestProperty = "Dynamic Property"; // Setting dynamic property.
Console.WriteLine(sampleObject.TestProperty );
Console.WriteLine(sampleObject.TestProperty .GetType());
// This code example produces the following output:
// Dynamic Property
// System.String
dynamic test = new ExpandoObject();
((IDictionary<string, object>)test).Add("DynamicProperty", 5);
Console.WriteLine(test.DynamicProperty);
Solution 2
You can cast ExpandoObject
to a dictionary and populate it that way, then the keys that you set will appear as property names on the ExpandoObject...
dynamic data = new ExpandoObject();
IDictionary<string, object> dictionary = (IDictionary<string, object>)data;
dictionary.Add("FirstName", "Bob");
dictionary.Add("LastName", "Smith");
Console.WriteLine(data.FirstName + " " + data.LastName);
Comments
-
ward87 over 4 years
I wanna create an anonymous type that I can set the property name dynamically. it doesn't have to be an anonymous type. All I want to achieve is set any objects property names dynamically. It can be ExpandoObject, but dictionary will not work for me.
What are your suggestions?
-
ward87 over 13 yearsyes i know about that. but can i set ExpandoObjects property from a string array for example?
-
Jon Skeet over 13 years... well, or any other type implementing
IDynamicMetaObjectProvider
. -
stevemegson over 13 yearsExpandoObject implements
IDictionary<string,object>
, so yes you can treat it as a dictionary to populate it. -
ward87 over 13 yearswhat i am actually trying to say is can i set ExpandoObject 's property name dynamically? if i can can you please suply an example?
-
Andrew Bezzub over 13 yearsAdded example of expado object's usage
-
ward87 over 13 yearsthanks a lot man but this is not what i want unfortunately. i want to set the property name dynamically... In this case ".test"...
-
Andrew Bezzub over 13 yearsI've added another example. If it is not what you need then what do you mean under dynamic?
-
ward87 over 13 yearsyes this is exactly what i mean thanks a lot!
-
AaronLS over 10 years+1 That is pretty wild and I didn't know dynamics had this capability. Other languages have similar capabilities, and this certainly would have a few great use cases. On the other hand, it could also be abused pretty terribly as well, and should be used with due respect.