6

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?

mat
  • 1,645
  • 15
  • 36

3 Answers3

10

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());
Adam
  • 15,537
  • 2
  • 42
  • 63
  • Awesome. I knew that it would work, if I make the method generic, but I thought that I had to specify the type upon calling explicitely. Thanks a lot. – mat Sep 19 '12 at 12:55
4

Specify T on the method:

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

or perhaps on the class containing the method:

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

In both cases you'll need the same type constraints (if any) specified on the original class(es)

Jamiec
  • 133,658
  • 13
  • 134
  • 193
3

Change the signature of your method like this:

public void MyMethod<T>(B<T> x)
Mikhail Brinchuk
  • 656
  • 6
  • 16