Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# generics: using class generic in where clause of method generic

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)

like image 213
andresp Avatar asked Jun 04 '12 17:06

andresp


2 Answers

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;
like image 161
YavgenyP Avatar answered Sep 29 '22 23:09

YavgenyP


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??? >.

like image 29
Olivier Jacot-Descombes Avatar answered Sep 30 '22 01:09

Olivier Jacot-Descombes