How to create an instance for a typical type in C #

I need to create an instance without parameters for a generic class in C #.

How to do it.

+3
source share
1 answer

You can add a restriction : new():

void Foo<T>() where T : class, new() {
    T newT = new T();
    // do something shiny with newT
}

If you don't have a limit, then it Activator.CreateInstance<T>can help (minus compile-time checking):

void Foo<T>() {
    T newT = Activator.CreateInstance<T>();
    // do something shiny with newT
}

If you mean yourself of the type itself, then probably something like:

Type itemType = typeof(int);
IList list = (IList)Activator.CreateInstance(
         typeof(List<>).MakeGenericType(itemType));
+21
source

Source: https://habr.com/ru/post/1736946/


All Articles