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){ }
}
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){ }
}
Client
is a collection ofT
objects, and thoseT
objects must implement theIClientFactory
interface and have a public parameterless constructor.new() means
Ref Generic Constraints on MSDN
That's called a "'new' constraint". Here's the documentation on it.
(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.