Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I iterate over the properties of an anonymous object in C#?

I want to take an anonymous object as argument to a method, and then iterate over its properties to add each property/value to a a dynamic ExpandoObject.

So what I need is to go from

new { Prop1 = "first value", Prop2 = SomeObjectInstance, Prop3 = 1234 } 

to knowing names and values of each property, and being able to add them to the ExpandoObject.

How do I accomplish this?

Side note: This will be done in many of my unit tests (I'm using it to refactor away a lot of junk in the setup), so performance is to some extent relevant. I don't know enough about reflection to say for sure, but from what I've understood it's pretty performance heavy, so if it's possible I'd rather avoid it...

Follow-up question: As I said, I'm taking this anonymous object as an argument to a method. What datatype should I use in the method's signature? Will all properties be available if I use object?

like image 714
Tomas Aschan Avatar asked Apr 07 '10 17:04

Tomas Aschan


People also ask

When you define an anonymous type the compiler converts the type into?

Anonymous types are class type, directly derived from “System. Object” so they are reference types. If two or more Anonymous types have same properties in same order in a same assembly then compiler treats them as same type. All properties of anonymous types are read only.

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.

What are anonymous types in C#?

What is Anonymous Types in C#? Anonymous types in C# are the types which do not have a name or you can say the creation of new types without defining them. It is introduced in C# 3.0. It is a temporary data type which is inferred based on the data that you insert in an object initializer.


1 Answers

foreach(var prop in myVar.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)) {    Console.WriteLine("Name: {0}, Value: {1}",prop.Name, prop.GetValue(myVar,null)); } 
like image 108
BFree Avatar answered Sep 28 '22 05:09

BFree