Should’t this be valid C# code?
class A<T> where T : class {
public void DoWork<K>() where K : T {
var b = new B<K>(); // <- compile time error
}
}
class B<U> where U : class {
}
The compiler spits this error:
error CS0452: The type ‘K’ must be a reference type in order to use it as parameter ‘U’ in the generic type or method ‘ConsoleApplication1.B’
Shouldn’t the compiler be able to figure out that K is constraint to be of type T or derived from T so it should obviously be a reference type (T is constrained to be a reference type)?
The constraints are applied when the type parameter is specified. A type has not been specified for K even though K is being specified for U. As U requires its type to be a reference type, the compiler is looking to confirm that K is indeed a reference type, but it cannot. Therefore, you need to explicitly state that it will be.
The specification states in section 4.4.4:
and later:
This last point indicates that K will not inherit the constraints from T.
Update
While my conclusions appear correct, my evidence is a little shaky as was clarified in a now deleted response from Eric Lippert’s response. There, Eric stated that the correct part of the specification is: