Type constraints (new-keyword) C# with Example



Type constraints (new-keyword) C# with Example

By using the new() constraint, it is possible to enforce type parameters to define an empty (default) constructor. 
class Foo 
{ 
public Foo () { } 
} 
class Bar 
{ 
 

public Bar (string s) { ... } 
} 
class Factory 
where T : new() 
{ 
public T Create() 
{ 
return new T(); 
} 
} 
Foo f = new Factory().Create(); // Valid. 
Bar b = new Factory().Create(); // Invalid, Bar does not define a default/empty constructor. 
The second call to to Create() will give compile time error with following message: 
'Bar' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 
'T' in the generic type or method 'Factory' 
There is no constraint for a constructor with parameters, only parameterless constructors are supported. 

0 Comment's

Comment Form

Submit Comment