Using a generic base class as a parameter of a method
Asked Answered
D

3

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?

Dettmer answered 19/9, 2012 at 12:38 Comment(0)
O
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());
Operation answered 19/9, 2012 at 12:40 Comment(1)
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.Dettmer
S
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)

Subchaser answered 19/9, 2012 at 12:41 Comment(0)
O
3

Change the signature of your method like this:

public void MyMethod<T>(B<T> x)
Ophiolatry answered 19/9, 2012 at 12:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.