What does new() mean?
There is an AuthenticationBase
class in WCF RIA Services. The class definition is as follows:
// assume using System.ServiceModel.DomainServices.Server.ApplicationServices
public abstract class AuthenticationBase<T>
: DomainService, IAuthentication<T>
where T : IUser, new()
What does new()
mean in this code?
Solution 1:
It's the new constraint.
It specifies that T
must not be abstract and must expose a public parameterless constructor in order to be used as a generic type argument for the AuthenticationBase<T>
class.
Solution 2:
Using the new() keyword requires a default constructor to be defined for said class. Without the keyword, trying to class new() will not compile.
For instance, the following snippet will not compile. The function will try to return a new instance of the parameter.
public T Foo <T> ()
// Compile error without the next line
// where T: new()
{
T newInstance = new T();
return newInstance;
}
This is a generic type constraint. See this MSDN article.
Solution 3:
It means that a type used to fill the generic parameter T
must have a public and parameterless constructor. If the type does not implement such a constructor, this will result in a compile-time error.
If the new()
generic constraint is applied, as in this example, that allows the class or method (the AuthenticationBase<T>
class in this case) to call new T();
to construct a new instance of the specified type. There is no other way, short of reflection (this includes using System.Activator
, to construct a new object of a generic type.