Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the new() constraint do on a class definition?

I saw this code example and was wondering what the purpose of the new() constraint was:

public class Client<T> : IClient where T : IClientFactory, new()
{
    public Client(int UserID){ }
}
like image 633
Ian R. O'Brien Avatar asked Dec 20 '22 12:12

Ian R. O'Brien


2 Answers

That's called a "'new' constraint". Here's the documentation on it.

The new constraint specifies that any type argument in a generic class declaration must have a public parameterless constructor. To use the new constraint, the type cannot be abstract.

(Emphasis mine)

Basically, you need it whenever you're creating a new T somewhere in the class, to ensure that you're only able to pass in things which the compiler can create a new instance of.

like image 93
Bobson Avatar answered Dec 23 '22 02:12

Bobson


Client is a collection of T objects, and those T objects must implement the IClientFactory interface and have a public parameterless constructor.

like image 44
Major Productions Avatar answered Dec 23 '22 00:12

Major Productions