Creating an anonymous type dynamically?

C#DynamicAnonymous Types

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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 - C#

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionward87View Question on Stackoverflow
Solution 1 - C#Andrew BezzubView Answer on Stackoverflow
Solution 2 - C#stevemegsonView Answer on Stackoverflow