Using a common base class as a method parameter

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 is a method that can take any class derived from B<T>, for example, C1or C2as a parameter. But declaring the method as

public void MyMethod(B<T> x)

does not work, it gives a compiler error

Error CS0246: The type or namespace name `T 'could not be found. Do you miss directions for use or build links? (CS0246)

I'm stuck here. Creating a non-core base word for B<T>will not work, as I could not get from A<T>that way. The only (ugly) solution I could think of was to define an empty dummy interface that is "implemented" with B<T>. Is there a more elegant way?

+5
3

:

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

:

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

T :

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

, , , :

public class Foo<T>
{
    public void MyMethod(B<T> x){}
}

( ), ()

+4

Change the signature of your method as follows:

public void MyMethod<T>(B<T> x)
+3
source

All Articles