Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I determine at runtime if an interface member is implemented?

I have an interface called IStructuredReader that reads some structured data from a file and displays it in a form. It has a member called Sync() that, when implemented, scans the data for a user-specified data pattern.

Some implementations of IStructuredReader don't have sync capability. Those implementations throw NotImplementedException for the Sync() method. I would like to be able to check for this method being implemented, so that I can dim the button on the form if it is not.

I can think of a number of ways that this could be done, all of which seem clumsy and complicated:

  1. Separate the Sync method into its own interface, inherit it for those implementations that support the capability, and attempt to cast the reader object to it to identify the capability,

  2. Write a NotImplementedAttribute, decorate the member with it, and check for the presence of the attribute using Reflection,

  3. Add a HasSyncCapability boolean property to the interface.

Is there a canonical way this is done?

like image 572
Robert Harvey Avatar asked Feb 17 '23 20:02

Robert Harvey


2 Answers

This sounds like you really should have two interfaces. Your Sync() method is obviously adding functionality over your base interface, which suggests that this is really a separate concern, as it's not a requirement of IStructuredReader. I would suggest adding a second interface for the types which support this, which would then be easy to check for in your view layer.

like image 54
Reed Copsey Avatar answered Feb 20 '23 09:02

Reed Copsey


The canonical way is for the interface to expose the methods that will be implemented, so the cleanest solution I see is to create another interface called maybe Syncronizable with just that method. If your object implements that interface you know the method is there, and this is not clumsy at all. Using reflection or the extra attribute are indeed not as clean as solutions, but it doesn't mean you shouldn't go for those if it makes your life easier ;)

like image 41
JohnIdol Avatar answered Feb 20 '23 09:02

JohnIdol