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();
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.
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.
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.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With