Creating an anonymous type dynamically? [duplicate]
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);
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);