Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it pointless to have both "class" and "new()" constraints in a generic class?

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?

like image 225
Andrei V Avatar asked Jul 16 '13 15:07

Andrei V


People also ask

Can a generic class have multiple 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.

Can generic classes be constrained?

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.

Which of the following constraint specifies that any type argument in a generic class declaration must have public parameter less constructor?

The new constraint specifies that a type argument in a generic class or method declaration must have a public parameterless constructor.

How do you restrict a generic class?

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.


2 Answers

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.

like image 170
Daniel Hilgarth Avatar answered Sep 23 '22 18:09

Daniel Hilgarth


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.

like image 21
Ehsan Avatar answered Sep 24 '22 18:09

Ehsan