C# generics: using class generic in where clause of method generic
.net-2.0, c#, generics
Solution
Actually it is possible. This code compiles and runs just fine:
public class A<T>
{
public void Act<U>() where U : T
{
Console.Write("a");
}
}
static void Main(string[] args)
{
A<IEnumerable> a = new A<IEnumerable>();
a.Act<List<int>>();
}
What is not possible is using covariance / contravariance in generics, as explained here:
IEnumerable<Derived> d = new List<Derived>();
IEnumerable<Base> b = d;
Problem
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>' requires`2' type argument(s)