8. dec 2009 21:38

At a course today I was asked how you instantiate an anonumous type using reflection.

The answer is simply that you do it in the same way that you instantiate all other types. The one thing you have to know though is that an anonymous type is defined with a single constructor with parameters corresponding to the parameters in the object initializer, so you have to provide these parameters when instantiating the anonymous type.

Lets say we have an object duck instantiated from an anonymous type in the following way:

var duck = new { Name = "Donald Duck", Address = "Duckburg" };

Now you can create a new object from that anonymous type:

System.Type duckType = duck.GetType();

object[ ] parameters = { "Daisy Duck", "Duckburg" };

object newDuckObject = System.Activator.CreateInstance(duckType, parameters);

If you want to be able to specify the parameters by name instead of by position then you could quite easily achieve that by using e.g. a dictionary for specifying the parameters and a bit of reflection for mapping each name to the position of each of the constructor parameters.

Is it useful to be able to instantiate anonymous types using reflection? Probably not - but you never know ;^)

Abonnér på mit RSS feed.   Læs også de øvrige indlæg i denne Blog.