Testing if an object implements an interface

  • Thread starter Thread starter Steve B.
  • Start date Start date
S

Steve B.

Hello

I'm trying to test if an object is an instance of a class that implements a
specific interface.

I use this code :

if(!(f.GetType().IsSubclassOf(typeof(IParametrableForm))))

throw new SystemException("The form is not parametrable");

The exception is always thrown, instead the tested object actually implement
the interface :

public class frmProduct : System.Windows.Forms.Form, IParametrableForm

{

....



What's wrong with my code ?

Thanks,
Steve
 
That is because it is not a subclass of the interface. Deriving from a class
and implementing an interface are two different things.

One way to achieve what you want is to call to GetInterfaces and check if
IParametrableForm is in there.

Cheers
Daniel
 
Thanks for the answer

A little bit more easy way to reach my goal is this one:

if((f as IParametrableForm) == null)
throw new ....

Thanks anyway :)
 
You can also do :

if(typeof(IParametrableForm).IsAssignableFrom(f))
{
....Do whatever
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top