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)
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;
It works for me (VS 2008).
Do you have a problem with a class visibility? (class not public, wrong namespace)
Which error message are you getting?
UPDATE
Given your implementation of Container<T>
I can write
class A { }
class B : A { }
class Test
{
public void MethodName( )
{
var obj = new Container<A>();
obj.Set(new B());
}
}
This works perfectly. Are you sure that B
derives from A
? Note that for instance List<B>
does NOT derive from List<A>
(see YavgenyP's answer).
The error message could be a hint, telling you that there exists another Container<T>
in another namespace requiring a second type argument for PerType<U, X??? >
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With