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() , which, when implemented, validates the data for a user-defined data template.

Some implementations of IStructuredReader do not have synchronization capabilities. These implementations throw a NotImplementedException for the Sync() method. I would like to be able to check if this method is implemented so that I can mute the button in the form if it is not.

I can come up with several ways in which this could be done, all of which seem awkward and complex:

  • Separate the Sync method into your own interface, inherit it for those implementations that support this feature, and try passing the reader object to it to identify this feature,

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

  • Add the boolean HasSyncCapability boolean to the interface.

Is there a canonical way to do this?

+4
source share
2 answers

It sounds like you really have two interfaces. Your Sync() method obviously adds functionality to your base interface, which suggests that this is indeed a separate issue, as this is not a requirement of IStructuredReader . I would suggest adding a second interface for types that support this, which would be easy to check at your presentation level.

+6
source

The canonical way is for the interface to display the methods that will be implemented, so the cleanest solution that I see is to create another interface that can be Syncronizable with just this method. If your object implements this interface, you know that the method exists, and this is not at all clumsy. Using reflection or an additional attribute is really not as clean as a solution, but this does not mean that you should not go after them if it makes your life easier;)

+2
source

All Articles