Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it impossible to use Generics dynamically? [duplicate]

Tags:

c#

generics

I need to create at runtime instances of a class that uses generics, like class<T>, without knowing previously the type T they will have, I would like to do something like that:

public Dictionary<Type, object> GenerateLists(List<Type> types)
{
    Dictionary<Type, object> lists = new Dictionary<Type, object>();

    foreach (Type type in types)
    {
        lists.Add(type, new List<type>()); /* this new List<type>() doesn't work */
    }

    return lists;
}

...but I can't. I think it is not possible to write in C# inside the generic brackets a type variable. Is there another way to do it?

like image 245
Victor Rodrigues Avatar asked Oct 24 '08 15:10

Victor Rodrigues


People also ask

Can you explain Generics in net?

NET framework provides generics to create classes, structures, interfaces, and methods that have placeholders for the types they use. Generics are commonly used to create type-safe collections for both reference and value types. The . NET framework provides an extensive set of interfaces and classes in the System.

Why we use Generics in c#?

Generics allow you to define the specification of the data type of programming elements in a class or a method, until it is actually used in the program. In other words, generics allow you to write a class or method that can work with any data type.

How to use t generic in c#?

T is called type parameter, which can be used as a type of fields, properties, method parameters, return types, and delegates in the DataStore class. For example, Data is generic property because we have used a type parameter T as its type instead of the specific data type.


1 Answers

You can't do it like that - the point of generics is mostly compile-time type-safety - but you can do it with reflection:

public Dictionary<Type, object> GenerateLists(List<Type> types)
{
    Dictionary<Type, object> lists = new Dictionary<Type, object>();

    foreach (Type type in types)
    {
        Type genericList = typeof(List<>).MakeGenericType(type);
        lists.Add(type, Activator.CreateInstance(genericList));
    }

    return lists;
}
like image 168
Jon Skeet Avatar answered Oct 12 '22 22:10

Jon Skeet