Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does generic typing to a new instance achieve?

Tags:

c#

.net

generics

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

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

//etc

}

What does this achieve?

like image 843
Dan Avatar asked Nov 03 '10 17:11

Dan


1 Answers

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.

like image 88
JaredPar Avatar answered Sep 21 '22 10:09

JaredPar