What does typical typing provide for a new instance?

I noticed that someone did this in C # - pay attention to the new ()

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

What does it mean?

+6
generics c #
source share
3 answers

This restricts the shared MyClass<T> access only to instances of T that have an accessible constructor without parameters. This allows you to safely use the following expression in a type.

 new T() 

Without the new constraint, this will not be allowed, since the CLR could not verify the type T had an applicable constructor.

+10
source share

This means that T must have an open constructor without parameters. For example (from MSDN), the following T-object creation should be possible:

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

See the new restriction on MSDN for more information.

+4
source share

It allows you to enter:

 T obj = new T(); 

which generates a compiler error without the new() clause.

+1
source share

All Articles