Testing for interface support

  • Thread starter Thread starter Glenn Thimmes
  • Start date Start date
G

Glenn Thimmes

Hello,

I am trying to understand the proper way to test an object to find out if it
supports a specific interface. Right now, the only way I know to accomplish
this is to attempt casting it to that interface and then catch the exception
if one is thrown. This doesn't seem like the correct way to be doing this.

Any suggestions? I assume I'm missing something pretty basic.

Thanks in advance!
-Glenn
 
Glenn Thimmes said:
I am trying to understand the proper way to test an object to find out if it
supports a specific interface. Right now, the only way I know to accomplish
this is to attempt casting it to that interface and then catch the exception
if one is thrown. This doesn't seem like the correct way to be doing this.

Any suggestions? I assume I'm missing something pretty basic.

if (x is IWhatever)

or

IWhatever foo = x as IWhatever;
if (foo != null)
{
....
}
 
right.
try this:

IMyInterface myInterface = myObject as IMyInterface;

if (myInterface==null)
{
//does not implement
}
else
{
//implements
}


HTH

Picho
 
The best way for the case that you are describing is to use the "as"
keyword. Example.

public void Foo(object obj)
{
IPerson person = obj as IPerson;
if ( person != null )
{
// obj supports the IPerson interface
}
}

When the object does not support the specific interface, person would be
null
 
Back
Top