Dan
Dan

Reputation: 13343

What does generic typing to a new instance achieve?

I have noticed someone has done this in C# - notice the new()

public class MyClass<T> where T: new(){

//etc

}

What does this achieve?

Upvotes: 6

Views: 141

Answers (3)

henginy
henginy

Reputation: 2071

It enables you to type:

T obj = new T();

which would generate a compiler error without the new() clause.

Upvotes: 1

JaredPar
JaredPar

Reputation: 755179

This constrains the generic MyClass<T> to only work with T instances that have an available parameterless constructor. This allows you to safely use the following expression within the type

new T()

Without the new constraint this would not be allowed because the CLR couldn't verify the type T had an applicable constructor.

Upvotes: 10

Michael Goldshteyn
Michael Goldshteyn

Reputation: 74410

It means that T must have a public parameterless constructor. For example (out of MSDN), the following creation of a new T object must be possible:

class ItemFactory<T> where T : new()
{
    public T GetNewItem()
    {
        return new T();
    }
}

For more info, please see new constraint in MSDN.

Upvotes: 4

Related Questions