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

Posted by Tomas Lycken on Stack Overflow See other posts from Stack Overflow or by Tomas Lycken
Published on 2010-04-07T17:23:39Z Indexed on 2010/04/07 17:33 UTC
Read the original article Hit count: 523

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?

© Stack Overflow or respective owner

Related posts about anonymous-types

Related posts about c#