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?
There can be more than one constraint associated with a type parameter. When this is the case, use a comma-separated list of constraints. In this list, the first constraint must be class or struct or the base class.
You can constrain the generic type by interface, thereby allowing only classes that implement that interface or classes that inherit from classes that implement the interface as the type parameter. The code below constrains a class to an interface.
The new constraint specifies that a type argument in a generic class or method declaration must have a public parameterless constructor.
Whenever you want to restrict the type parameter to subtypes of a particular class you can use the bounded type parameter. If you just specify a type (class) as bounded parameter, only sub types of that particular class are accepted by the current generic class.
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.
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.
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