I have a method similar to the following:
public MyData GetTransformedInfo(MyAbstractClass obj) {
// Calculate and return relevant stuff
}
It’s unlikely but MyAbstractClass‘s children can have descendant classes.
I also have an interface, IMyInterface, that’d make sense to be implemented by a lot of different classes, including, but not limited to, some of MyAbstractClass‘s children and their descendants.
The problem is, I need the above function to only accept MyAbstractClass‘s descendants that ALSO implements IMyInterface.
I wished a simple GetTransformedInfo(MyAbstractClass:IMyInterface obj) would work but of course it won’t.
I thought about using reflection, bailing out when not matching. But that’s bad for several reasons. To name a few: it’s not enforced at compile time, slow, allocates memory just for such a simple compatibility check.
Is my only option writing
public abstract class MyAbstractClassWithIMyInterface : MyClass, IMyInterface {}
public MyData GetTransformedInfo(MyAbstractClassWithIMyInterface obj) {
// Calculate and return relevant stuff
}
and making those specific classes inherit from it? Is there any other alternative?
I believe it’d be the same problem if I had two interfaces and would want the method to only accept objects that implements both at the same time. So I guess this is the best I can get.
>Solution :
You could use a generic function with constraints
public MyData GetTransformedInfo<T>(T obj)
where T : MyAbstractClass, IMyInterface
{
// Calculate and return relevant stuff
}