Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set/create a Generics instance?

Tags:

c#

I Have following problem:

class Request<T>
{
    private T sw; 

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

}

is it possible to do it?

like image 259
Racooon Avatar asked Oct 19 '11 16:10

Racooon


2 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 parameterless constructor (no, you can't specify any other kind of constructor).

like image 117
jason Avatar answered Sep 23 '22 18:09

jason


You need to declare the constraint where T : new() in the class declaration. This is restricting T to types with a public default constructor. For example:

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

    public Request()
    {
        sw = new T();
    }
 }

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

like image 26
Paul Bellora Avatar answered Sep 23 '22 18:09

Paul Bellora