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?
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.
Generic methods in non-generic classYes, you can define a generic method in a non-generic class in Java.
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.
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.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With