Search code examples
c#.netmonoderived-classgeneric-type-argument

Using a generic base class as a parameter of a method


I have the following classes

public class A<T>
{
}
public class B<T> : A<T>
{
}
public class C1 : B<string>
{
}
public class C2 : B<int>
{
}

What I would like to do, is have a method which can take any class derived from B<T>, like C1 or C2 as a parameter. But declaring a method as

public void MyMethod(B<T> x)

does not work, it yields the compiler error

Error CS0246: The type or namespace name `T' could not be found. Are you missing a using directive or an assembly reference? (CS0246)

I am quite stuck here. Creating a non-generic baseclass for B<T> won't work, since I wouldn't be able to derive from A<T> that way. The only (ugly) solution I could think of is to define an empty dummy-interface which is "implemented" by B<T>. Is there a more elegant way?


Solution

  • Use a generic method:

    public void MyMethod<T> (B<T> x)
    

    And you can call it like so:

    MyMethod(new B<string>());
    MyMethod(new C1());
    MyMethod(new C2());