Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why must new() constraint be specified last?

C# compiler requires new() constraint to be specified last. According to MSDN:

When used together with other constraints, the new() constraint must be specified last.

Why is there such restriction?

like image 866
empi Avatar asked Feb 24 '11 19:02

empi


People also ask

What is new () constraint in C#?

The new constraint specifies that a type argument in a generic class or method declaration must have a public parameterless constructor. To use the new constraint, the type cannot be abstract.

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 the purpose of the class constraint on a type parameter?

Object, you'll apply constraints to the type parameter. For example, the base class constraint tells the compiler that only objects of this type or derived from this type will be used as type arguments. Once the compiler has this guarantee, it can allow methods of that type to be called in the generic class.

What is type parameter in C#?

In a generic type or method definition, a type parameter is a placeholder for a specific type that a client specifies when they create an instance of the generic type.


1 Answers

Because the specification says so. It probably says so because it makes parsing the constraints a little easier. There is little value in allowing you to specify the constraints in any order and I can imagine some cost (including opportunity cost!) in making it possible.

Note, in fact, that the specification doesn't just say that you have to have the constructor constraint last, if you have it. It actually says that you have to have the constraints in the following order

  1. Primary constraint.
  2. Secondary constraints.
  3. Constructor constraint.

Where a primary constraint is one that specifies the type parameter must be a reference type or a value type, secondary constraints are ones that specify a base class or interfaces, and the constructor constraint is the one under discussion here.

The relevant section of the specification is §10.1.5 and is definitely worthwhile reading.

like image 148
jason Avatar answered Oct 10 '22 10:10

jason