bleeeah
bleeeah

Reputation: 3604

Dynamically create an object from an anonymous object

Using a type builder I am OK with creating a type dynamically. Would it be possible to do this from an anonymous type?

I have this so far;

//CreateType generates a type (so that I can set it's properties once instantiated) from an //anonymous object. I am not interested in the initial value of the properties, just the Type.
 Type t = CreateType(new {Name = "Ben", Age = 23});
 var myObject = Activator.CreateInstance(t);

Is it possible to now use Type "t" as a type argument?

My method:

public static void DoSomething<T>() where T : new() 
{
}

I would like to call this method using the dynamically created Type "t". So that I can call;

DoSomething<t>(); //This won't work obviously

Upvotes: 4

Views: 294

Answers (1)

Botz3000
Botz3000

Reputation: 39610

Yes, it is possible. To use the type as a type argument, you need to use the MakeGenericType method:

// Of course you'll use CreateType here but this is what compiles for me :)
var anonymous = new { Value = "blah", Number = 1 };
Type anonType = anonymous.GetType();

// Get generic list type
Type listType = typeof(List<>);
Type[] typeParams = new Type[] { anonType };
Type anonListType = listType.MakeGenericType(typeParams);

// Create the list
IList anonList = (IList)Activator.CreateInstance(anonListType);

// create an instance of the anonymous type and add it
var t = Activator.CreateInstance(anonType, "meh", 2); // arguments depending on the constructor, the default anonymous type constructor just takes all properties in their declaration order
anonList.Add(t);

Upvotes: 2

Related Questions