Creating an anonymous type dynamically?

42,246

Solution 1

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

Solution 2

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);
Share:
42,246
ward87
Author by

ward87

Agile software development...

Updated on March 28, 2020

Comments

  • ward87
    ward87 over 4 years

    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?

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