How to tell if an object inherits an interface

  • Thread starter Thread starter Ron
  • Start date Start date
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
 
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
}
}
 
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>())
{
...
}
 
Back
Top