How to tell if an object inherits an interface

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Ron

    How to tell if an object inherits an interface

    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

  • Darren

    #2
    Re: How to tell if an object inherits an interface

    if ( control is ICustomControl )
    {
    .....
    }


    Ron wrote:
    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

    Comment

    • Ron

      #3
      Re: How to tell if an object inherits an interface

      Thanks Darren!

      "Darren" <Darren@nospam. nospamwrote in message
      news:%23xRCcd6g IHA.5780@TK2MSF TNGP06.phx.gbl. ..
      if ( control is ICustomControl )
      {
      ....
      }
      >
      >
      Ron wrote:
      >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

      Comment

      • Andy

        #4
        Re: How to tell if an object inherits an interface

        On Mar 11, 2:40 pm, Darren <Dar...@nospam. nospamwrote:
        if ( control is ICustomControl )
        {
        ....
        >
        }
        Ron wrote:
        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
        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
        }
        }

        Comment

        Working...