I think there are people who may be able to answer this, this is a question out of curiosity:
The generic CreateInstance
method from System.Activator
, introduced in .NET v2 has no type constraints on the generic argument but does require a default constructor on the activated type, otherwise a MissingMethodException
is thrown. To me it seems obvious that this method should have a type constraint like
Activator.CreateInstance<T>() where T : new() {
...
}
Just an omission or some anecdote lurking here?
Update
As pointed out, the compiler does not allow you to write
private T Create<T>() where T : struct, new()
error CS0451: The 'new()' constraint cannot be used with the 'struct' constraint
However, see comments a struct can be used as type argument to a generic method specifying a new() constraint. Under this circumstance the given answer seems the only valid reason to not constrain the method...
Thanks for looking over this!
I could be wrong, but the main benefit as I see it is that it allows you to do something like this:
Note that if
Activator.CreateInstance<T>
had awhere T : new()
constraint, then theCache<T>
class above would also need that constraint, which would be overly restrictive sinceCreate
is a virtual method and some derived class might want to use a different means of instantiation, such as calling a type's internal constructor or using a static builder method.