Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 972
synergetic Avatar asked Nov 21 '10 07:11

synergetic


People also ask

What does where T new () mean?

where T : new() Means that the type T must have a parameter-less constructor. Having this constraint will allow you to do something like T field = new T(); in your code which you wouldn't be able to do otherwise.

What is new () in C#?

The new operator creates a new instance of a type. You can also use the new keyword as a member declaration modifier or a generic type constraint.

What does new mean in programming?

new is a Java keyword. It creates a Java object and allocates memory for it on the heap. new is also used for array creation, as arrays are also objects.

What is the mean of new?

: having recently come into existence : recent, modern. I saw their new baby for the first time. a(1) : having been seen, used, or known for a short time : novel.


2 Answers

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.

like image 190
Frédéric Hamidi Avatar answered Sep 23 '22 22:09

Frédéric Hamidi


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.

like image 26
AK. Avatar answered Sep 20 '22 22:09

AK.