How to install / create an instance of Generics?

I have the following problem:

class Request<T> { private T sw; public Request() { //How can i create here the instance like sw = new T(); } } 

can this be done?

+6
source share
3 answers

Add a new constraint:

 class Request<T> where T : new() { private T sw; public void Request() { sw = new T(); } } 

This tells the compiler that T will always have an accessible constructor without parameters (no, you cannot specify any other constructor).

+7
source

You need to declare the where T : new() constraint in the class declaration. This restricts T type with the default public constructor. For instance:

 class Request<T> where T : new() { private T sw; public Request() { sw = new T(); } } 

Additional information: http://msdn.microsoft.com/en-us/library/d5x73970.aspx

+5
source

You need to tell the compiler that T always implements a constructor without parameters.

 class Request<T> where T : new() 
+5
source

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


All Articles