C# generics type constraint -
should't valid c# code?
class a<t> t : class { public void dowork<k>() k : t { var b = new b<k>(); // <- compile time error } } class b<u> u : class { }
the compiler spits error:
error cs0452: type 'k' must reference type in order use parameter 'u' in generic type or method 'consoleapplication1.b'
shouldn't compiler able figure out k constraint of type t or derived t should reference type (t constrained reference type)?
the constraints applied when type parameter specified. type has not been specified k though k being specified u. u requires type reference type, compiler looking confirm k indeed reference type, cannot. therefore, need explicitly state be.
the specification states in section 4.4.4:
for each clause, type argument corresponds named type parameter checked against each constraint...
and later:
a compile-time error occurs if 1 or more of type parameter’s constraints not satisfied given type arguments.
since type parameters not inherited, constraints never inherited either.
this last point indicates k not inherit constraints t.
update
while conclusions appear correct, evidence little shaky clarified in deleted response eric lippert's response. there, eric stated correct part of specification is:
a type parameter known reference type if has reference type constraint or effective base class not object or
system.valuetype
.
Comments
Post a Comment