Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 580
mat Avatar asked Sep 19 '12 12:09

mat


People also ask

How do you indicate that a class has a generic type parameter?

A generic type is declared by specifying a type parameter in an angle brackets after a type name, e.g. TypeName<T> where T is a type parameter.

Can you have a generic method in a non generic class?

Generic methods in non-generic classYes, you can define a generic method in a non-generic class in Java.

What is a generic method and when should it be used?

Generic methods allow type parameters to be used to express dependencies among the types of one or more arguments to a method and/or its return type. If there isn't such a dependency, a generic method should not be used. It is possible to use both generic methods and wildcards in tandem. Here is the method Collections.

What is the purpose of the class constraint on a type parameter?

Object, you'll apply constraints to the type parameter. For example, the base class constraint tells the compiler that only objects of this type or derived from this type will be used as type arguments. Once the compiler has this guarantee, it can allow methods of that type to be called in the generic class.


1 Answers

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());
like image 95
Adam Avatar answered Sep 21 '22 01:09

Adam