Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically create an object from an anonymous object

Tags:

c#-4.0

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
like image 819
bleeeah Avatar asked Aug 16 '26 04:08

bleeeah


1 Answers

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);
like image 136
Botz3000 Avatar answered Aug 18 '26 15:08

Botz3000



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!