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?
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.
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.
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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With