Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

new() keyword at the end of method declaration [duplicate]

A workmate just gave me some C# classes that I must use in a .NET application.
There's a typo that I have never seen, and I can't found any explication on the internet...

Here's the code :

public void GoTo<TView>() where TView : Form, new()
{
    var view = Activator.CreateInstance<TView>();

    //si on vient de creer une startup view alors on affiche l'ancienne
    //la reference a la nouvelle sera detruite en sortant de la fonction GoTo
    if (view is StartupForm)
    {
        ShowView(_StartupForm);
    }
    else ShowView(view);

}

What is the new() keyword for, right at the end of the method declaration ?

like image 282
Scaraux Avatar asked Nov 30 '22 16:11

Scaraux


2 Answers

It is type parameter constraint. Literally it means TView must have a public parameterless constructor.

like image 79
Andrey Korneyev Avatar answered Dec 04 '22 02:12

Andrey Korneyev


See the MSDN:

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.

So when you say:

void myMethod<T>(T item) where T : class, new();

then it means that you are putting a constraint on generic parameter T. So T should be a reference type and cannot be a value type(int, float, double etc). Also T should have a public parameter-less default constructor.

like image 25
Rahul Tripathi Avatar answered Dec 04 '22 02:12

Rahul Tripathi