Can anyone explain why isn’t this possible (at least in .Net 2.0):
public class A<T>
{
public void Method<U>() where U : T
{
...
}
}
...
A<K> obj = new A<K>();
obj.Method<J>();
with K being the superclass of J
EDIT
I’ve tried to simplify the problem in order to make the question more legible, but I’ve clearly overdo that. Sorry!
My problem is a little more specific I guess. This is my code (based on this):
public class Container<T>
{
private static class PerType<U> where U : T
{
public static U item;
}
public U Get<U>() where U : T
{
return PerType<U>.item;
}
public void Set<U>(U newItem) where U : T
{
PerType<U>.item = newItem;
}
}
and I’m getting this error:
Container.cs(13,24): error CS0305: Using the generic type
Container<T>.PerType<U>' requires2′ type argument(s)
Actually it is possible. This code compiles and runs just fine:
What is not possible is using covariance / contravariance in generics, as explained here: