Reputation: 7506
I am wondering if it makes any sense to have both "class" and "new()" constraints when defining a generic class. As in the following example:
class MyParanoidClass<T> where T : class, new()
{
//content
}
Both constraints specify that T should be a reference type. While the "class" constraint does not imply that a implicit constructor exists, the "new()" constraint does require a "class" with an additional public constructor definition.
My final (formulation for the) question is: do I have any benefits from defining a generic class as in the above statement, or does "new()" encapsulate both constraints?
Upvotes: 5
Views: 324
Reputation: 32681
No they are not useless.
First parameter class ensures that the type argument must be a reference type, including any class, interface, delegate, or array type,
whereas second parameter new() ensures that it has a parameter less default constructor. It will not work for any class that doesn't have parameter less default constructor.
Upvotes: 1
Reputation: 174329
new()
doesn't imply a reference type, so: No, class
is not redundant when using new()
.
The following code demonstrates that:
void Main()
{
new MyParanoidClass<S>();
}
struct S {}
class MyParanoidClass<T> where T : new()
{
//content
}
This code compiles, proving that new()
doesn't care if you use a reference or a value type.
Upvotes: 7