views:

66

answers:

2

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
yes i know about that. but can i set ExpandoObjects property from a string array for example?
ward87
... well, or any other type implementing `IDynamicMetaObjectProvider`.
Jon Skeet
ExpandoObject implements `IDictionary<string,object>`, so yes you can treat it as a dictionary to populate it.
stevemegson
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
Added example of expado object's usage
Andrew Bezzub
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
I've added another example. If it is not what you need then what do you mean under dynamic?
Andrew Bezzub
yes this is exactly what i mean thanks a lot!
ward87
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