I\'m currently using Generics to make some dynamic methods, like creating an object and filling the properties with values.
Is there any way to \"dynamically\" creat
You can use MakeGenericType
:
Type openListType = typeof(List<>);
Type genericListType = openListType.MakeGenericType(obj.GetType());
object instance = Activator.CreateInstance(genericListType);
When you use the object initializer, it's just using a default constructor (no parameters), then setting the individual properties after the object is constructed.
The code above is close - but var
won't work here, since it's just a compile-time type inferrence. Since you're already using reflection, you can just use System.Object
:
object propertyValue = values[p.Name];
The SetValue
call will work fine with System.Object
.
You can use the MakeGenericType method to get the generic type for a particular type argument:
var myObjListType = typeof(List<>).MakeGenericType(myObject.GetType());
var myObj = Activator.CreateInstance(myObjListType);
// MyObj will be an Object variable whose instance is a List<type of myObject>