locked
How to tell if a class implements an interface? RRS feed

  • Question

  • User-916962509 posted

    Hello,

    I've got a web user control (.ascx) which implements a couple of interfaces I wrote; namely IXMLBoundControl and ISectionOverridingControl.

    I've written a mini-CMS type application that dynamically loads controls onto the page based on information in a database. When I click a button on a web page (.aspx), I want to look at all the controls on that page, and determine if there is a control which implements the ISectionOverridingControl.

    I've got my loop and I'm looping through the controls; that's fine. However I'm not sure what the best way is to determine whether or not the control implements the interface. What I'm doing at the moment (and works) is to try to cast each control into the ISectionOverridingControl and catching InvalidCastException: If I don't get the catch; I consider it's worked. If the exception is thrown then it doesn't implement the interface.

    It's working, however, I consider this inefficient (relying on exceptions): surely there's a better way in VB.NET (I've seen an example in C# but it didn't convert to VB) to tell whether an instance of a class implements an interface or not?

    Appreciate any/all help.

    Regards
    bgs264

    Friday, December 4, 2009 5:09 AM

Answers

  • User1564875471 posted

    I want to look at all the controls on that page, and determine if there is a control which implements the ISectionOverridingControl.

    If TypeOf(yourcontrol) Is ISectionOverridingControl
     
         ' the control implmenets ISectionOverridingControl
    
    End If 


    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, December 4, 2009 6:02 AM

All replies

  • User1564875471 posted

    I want to look at all the controls on that page, and determine if there is a control which implements the ISectionOverridingControl.

    If TypeOf(yourcontrol) Is ISectionOverridingControl
     
         ' the control implmenets ISectionOverridingControl
    
    End If 


    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, December 4, 2009 6:02 AM
  • User-916962509 posted

    Cheers Cool 

    Friday, December 4, 2009 6:56 AM
  • User2115060517 posted

    Best solution that I've come up with is as follows: 

    public static class TypeExtensions
    {
        public static bool IsImplementationOf(this Type baseType, Type interfaceType)
        {
            return baseType.GetInterfaces().Any(interfaceType.Equals);
        }
    }

    public static class TypeExtensions

    {

        public static bool IsImplementationOf(this Type baseType, Type interfaceType)

        {

            return baseType.GetInterfaces().Any(interfaceType.Equals);

        }

    }

    More info at my blog!

    Tuesday, July 27, 2010 7:09 PM