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

Deukalion picture Deukalion · May 22, 2012 · Viewed 8k times · Source

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 };

Answer

Adi Lester picture Adi Lester · May 22, 2012

You can use MakeGenericType:

Type openListType = typeof(List<>);
Type genericListType = openListType.MakeGenericType(obj.GetType());
object instance = Activator.CreateInstance(genericListType);