ward87 ward87 - 1 year ago 140
C# Question

Creating an anonymous type dynamically?

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 etc. But dictionary will not work for me.
What are your suggestions?
thanks a lot

Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download