4

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 ?

Dmitry
  • 13,797
  • 6
  • 32
  • 48
Scaraux
  • 3,841
  • 4
  • 40
  • 80

3 Answers3

11

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

Andrey Korneyev
  • 26,353
  • 15
  • 70
  • 71
  • As an addition to this answer you can use following in your code: var variable = new TView(); while without new() constraint its not allowed by C# compiler. – serhiyb Jan 15 '16 at 14:05
8

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.

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
0

This is a type parameter constraint, specifically a constuctor-constraint, detailed in Section 10.1.5 of the C# Language Specification.

If the where clause for a type parameter includes a constructor constraint (which has the form new() ), it is possible to use the new operator to create instances of the type (§7.6.10.1). Any type argument used for a type parameter with a constructor constraint must have a public parameterless constructor (this constructor implicitly exists for any value type) or be a type parameter having the value type constraint or constructor constraint (see §10.1.5 for details).

This is just a way of guaranteeing that the type passed in can be constructed with a parameterless constructor.

casey
  • 6,855
  • 1
  • 24
  • 37