Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "where T : class, new()" mean?

Can you please explain to me what where T : class, new() means in the following line of code?

void Add<T>(T item) where T : class, new(); 
like image 684
Rawhi Avatar asked Jan 19 '11 16:01

Rawhi


People also ask

What does where T class mean?

it means that the type used as T when the generic method is used must be a class - i.e. it cannot be a struct or built in number like int or double // Valid: var myStringList = DoThis<string>(); // Invalid - compile error var myIntList = DoThis<int>(); Copy link CC BY-SA 2.5.

What is new () in C#?

The new operator creates a new instance of a type. You can also use the new keyword as a member declaration modifier or a generic type constraint.

What does the T mean in C#?

T is called type parameter, which can be used as a type of fields, properties, method parameters, return types, and delegates in the DataStore class. For example, Data is generic property because we have used a type parameter T as its type instead of the specific data type. Note.


2 Answers

That is a constraint on the generic parameter T. It must be a class (reference type) and must have a public parameter-less default constructor.

That means T can't be an int, float, double, DateTime or any other struct (value type).

It could be a string, or any other custom reference type, as long as it has a default or parameter-less constructor.

like image 64
NerdFury Avatar answered Sep 30 '22 23:09

NerdFury


Those are generic type constraints. In your case there are two of them:

where T : class 

Means that the type T must be a reference type (not a value type).

where T : new() 

Means that the type T must have a parameter-less constructor. Having this constraint will allow you to do something like T field = new T(); in your code which you wouldn't be able to do otherwise.

You then combine the two using a comma to get:

where T : class, new() 
like image 31
Justin Niessner Avatar answered Sep 30 '22 21:09

Justin Niessner