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?

2
  • 1
    Why does a dictionary not work for you? Commented Oct 26, 2010 at 14:35
  • 2
    cos i have to bind it to a telerik grid's datasource and also i add grid's columns dynamically. Commented Oct 26, 2010 at 14:36

2 Answers 2

68

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);
Sign up to request clarification or add additional context in comments.

7 Comments

yes i know about that. but can i set ExpandoObjects property from a string array for example?
... well, or any other type implementing IDynamicMetaObjectProvider.
ExpandoObject implements IDictionary<string,object>, so yes you can treat it as a dictionary to populate it.
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?
I've added another example. If it is not what you need then what do you mean under dynamic?
|
44

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);

1 Comment

+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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.