How do I get a class instance of generic type T?
To get a class instance of a generic type T
, you can use the new
operator and specify the type argument when creating an instance of the class. Here's an example:
class MyClass<T>
{
T field;
public MyClass(T t)
{
field = t;
}
}
// Creating an instance of MyClass<int>
MyClass<int> instance = new MyClass<int>(5);
// Creating an instance of MyClass<string>
MyClass<string> instance2 = new MyClass<string>("hello");
Alternatively, you can use the Activator.CreateInstance
method to create an instance of the class, like this:
MyClass<int> instance = (MyClass<int>)Activator.CreateInstance(typeof(MyClass<int>), 5);
MyClass<string> instance2 = (MyClass<string>)Activator.CreateInstance(typeof(MyClass<string>), "hello");
Keep in mind that if the class has multiple type parameters, you will need to specify values for all of them when creating an instance of the class.