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" create the Generic without knowing the type? For example:
List<String> = new List<String>()
is a predefinied way, but
List<(object.GetType())> = new List<(object.GetType()>()
isn't working... But can it?
This isn't working (Is there a similiar approach that works?)
public T CreateObject<T>(Hashtable values)
{
// If it has parameterless constructor (I check this beforehand)
T obj = (T)Activator.CreateInstance(typeof(T));
foreach (System.Reflection.PropertyInfo p in typeof(T).GetProperties())
{
// Specifically this doesn't work
var propertyValue = (p.PropertyType)values[p.Name];
// Should work if T2 is generic
// var propertyValue = (T2)values[p.Name];
obj.GetType().GetProperty(p.Name).SetValue(obj, propertyValue, null);
}
}
So, in short: how to take a "Type" and create an object from that without using Generics? I have only used Generics in methods so far, but is it possible to use the same way on variables? I have to define a Generic (T) before the method, so can I do the same on variables before "creating" them?
...or how to use "Activator" to create an object with Properties instead of Parameters. Like you do here:
// With parameters values
Test t = new Test("Argument1", Argument2);
// With properties
Test t = new Test { Argument1 = "Hello", Argument2 = 123 };
You can use MakeGenericType
:
Type openListType = typeof(List<>);
Type genericListType = openListType.MakeGenericType(obj.GetType());
object instance = Activator.CreateInstance(genericListType);
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With