6

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?

3 Answers 3

7

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).

Sign up to request clarification or add additional context in comments.

Comments

5

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

1 Comment

Thank you, an example would be very helpful.
5

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

class Request<T> where T : new() 

1 Comment

@BoltClock: a parameterless constructor perhaps? nullary constructor? what's the best word here?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.