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
+2
A:
Only ExpandoObject
can have dynamic properties (also see Jon Skeet's comment below).
Edit: Here is an example of Expand Object usage (from its MSDN description):
dynamic sampleObject = new ExpandoObject();
sampleObject.Test = "Dynamic Property"; // Setting dynamic property.
Console.WriteLine(sampleObject.test);
Console.WriteLine(sampleObject.test.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);
Andrew Bezzub
2010-10-26 14:35:58
yes i know about that. but can i set ExpandoObjects property from a string array for example?
ward87
2010-10-26 14:38:18
... well, or any other type implementing `IDynamicMetaObjectProvider`.
Jon Skeet
2010-10-26 14:38:39
ExpandoObject implements `IDictionary<string,object>`, so yes you can treat it as a dictionary to populate it.
stevemegson
2010-10-26 14:41:01
what i am actually trying to say is can i set ExpandoObject 's property name dynamically? if i can can you please suply an example?
ward87
2010-10-26 14:51:12
Added example of expado object's usage
Andrew Bezzub
2010-10-26 15:01:14
thanks a lot man but this is not what i want unfortunately. i want to set the property name dynamically... In this case ".test"...
ward87
2010-10-26 15:03:37
I've added another example. If it is not what you need then what do you mean under dynamic?
Andrew Bezzub
2010-10-26 15:07:21
yes this is exactly what i mean thanks a lot!
ward87
2010-10-27 06:07:28
A:
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
2010-10-26 15:04:13