Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an anonymous type dynamically? [duplicate]

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?

like image 748
ward87 Avatar asked Oct 26 '10 14:10

ward87


People also ask

What are difference between anonymous and dynamic types?

Anonymous type is a class type that contain one or more read only properties whereas dynamic can be any type it may be any type integer, string, object or class. Anonymous types are assigned types by the compiler.

When to use anonymous types C#?

Anonymous types typically are used in the select clause of a query expression to return a subset of the properties from each object in the source sequence. For more information about queries, see LINQ in C#. Anonymous types contain one or more public read-only properties.

Do anonymous types work with Linq?

You are allowed to use an anonymous type in LINQ. In LINQ, select clause generates anonymous type so that in a query you can include properties that are not defined in the class.


1 Answers

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); 
like image 54
Andrew Bezzub Avatar answered Oct 05 '22 12:10

Andrew Bezzub