Testing for interface support

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
 
J

Jon Skeet [C# MVP]

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)
{
....
}
 
P

Picho

right.
try this:

IMyInterface myInterface = myObject as IMyInterface;

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


HTH

Picho
 
J

Jared Parsons [MSFT]

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
 

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

Top