How to tell if an object inherits an interface

R

Ron

I have a situation where I need to test if a Control implements from a
specific Interface to avoid an invalid cast exception:

foreach (Control ctrl in this.Controls)
{
// Need to test to see if ctrl inherits interface ICustomControl here
ICustomControl control = (ICustomControl)ctrl;
}

Thanks!
Ron
 
A

Andy

if ( control is ICustomControl )
{
....

}

Alternately, he can do this:
foreach (Control ctrl in this.Controls)
{
// Need to test to see if ctrl inherits interface ICustomControl here
ICustomControl control = ctrl as ICustomControl;
if ( control != null ) {
// do something
}
}
 
J

Jon Skeet [C# MVP]

Andy said:
Alternately, he can do this:
foreach (Control ctrl in this.Controls)
{
// Need to test to see if ctrl inherits interface ICustomControl here
ICustomControl control = ctrl as ICustomControl;
if ( control != null ) {
// do something
}
}

Or with C# 3 and .NET 3.5:

foreach (ICustomControl ctrl in this.Controls.OfType<ICustomControl>())
{
...
}
 

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