Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating generic variables from a type - How? Or use Activator.CreateInstance() with properties { } instead of parameters ( )?

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 };
like image 649
Deukalion Avatar asked May 22 '12 19:05

Deukalion


2 Answers

You can use MakeGenericType:

Type openListType = typeof(List<>);
Type genericListType = openListType.MakeGenericType(obj.GetType());
object instance = Activator.CreateInstance(genericListType);
like image 76
Adi Lester Avatar answered Oct 21 '22 18:10

Adi Lester


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>
like image 6
Chris Shain Avatar answered Oct 21 '22 19:10

Chris Shain