How can I create a generic function only for a certain class hierarchy?

Viewed 98

Can I define a generic method that accepts only an argument only from a certain class hierarchy, the parent and child classes?

void DoSomething<T>(T input) {}

class A {}
class B : A {}

Here I want to use something like:

void DoSomething<A>(A input) {}

and I want this to work also for all cases within the class hierarchy:

A objA;
B objB;

DoSomething(objA);
DoSomething(objB);
1 Answers

You can do that by applying a generic constraint for base class

void DoSomething<T>(T input) where T : A
{
}
Related