Reputation: 15881
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?
Upvotes: 8
Views: 1286
Reputation: 11
YAQAPD: Yet Another Question About Parsing Direction
Every programming language has it's own rules. The direction of parsing is one of them. Let me explain in more detail (be patient).
Suppose that you write the following function in Pascal/Delphi:
function Sum2Numbers (n1, n2:integer) : integer;
begin
result:=n1+n2;
end;
Now, the same function in C:
int function Sum2Numbers (int n1, int n2)
{
return (n1+n2);
}
For the programmer's point of view, both function do the same thing (and really they do). However, behind the scenes, each compiler works on it's own way.
Pascal/Delphi and many other languages compile the code by parsing the text from LEFT TO RIGHT.
So, when we call the function in Pascal or Delphi, the compiler put in the stack, first n1
and second n2
.
The same function in C does it from RIGHT TO LEFT, i.e. the compilers put in the stack, first n2
and second n1
.
Both compilers read the parameters from stack in the ORDER they know, so all works fine.
All the "C-family" languages (C, C++, Managed C++, C++/CLI, C#, ...) they use the RIGHT TO LEFT order of parsing the code.
This is the reason why the new()
constraint MUST be specified in the FAR RIGHT of the constraint list.
The compiler must know IN ADVANCE that will need to create instances of classes, BEFORE use them.
Upvotes: 0
Reputation: 241611
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.
Upvotes: 15
Reputation: 1923
Because on other constraints (class for example) you can specify a constructor while on other constraints you can't (Interfaces).
So if new() came first, then a constraint on an interface, you would get an error because you can't have the new() constraint on the interface.
Upvotes: 0