In C# generics, we can declare a constraint for a type parameter T
to have a default constructor, by saying where T : new()
. However, no other kinds of constraints like this are valid - new(string)
for example, etc.
From a language design and/or implementation perspective, what is the reason for this?
Is there something in the way constructors work or in the way the type system is implemented that forbids this (or at least makes it harder)? If so, what is it? I recall reading somewhere that default(T)
actually compiles to new T()
for T : struct
. Is it related to this, maybe?
Or is it simply a design decision made in order to avoid making the language too complicated?
new(string)
is not a default constructor constraint. Your question is tantamount to saying "Why aren't there constraints that require specific constructor signatures?" Very likely because such a constraint would not be particularly useful.