69

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?

wonea
  • 4,783
  • 17
  • 86
  • 139
ward87
  • 3,026
  • 7
  • 27
  • 27

2 Answers2

67

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);
Community
  • 1
  • 1
Andrew Bezzub
  • 15,744
  • 7
  • 51
  • 73
43

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);
stevemegson
  • 11,843
  • 2
  • 38
  • 43
  • 4
    +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. – AaronLS Nov 06 '13 at 21:53