Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can I restrict an argument type to only class (and its descendants) that ALSO implements a given interface?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading