Question

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?

Was it helpful?

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());

OTHER TIPS

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)

Change the signature of your method like this:

public void MyMethod<T>(B<T> x)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top