Sunday, March 20, 2011

Test if object implements interface

What's the simplest way of testing if an object implements a given interface?

Is it possible to test if a class implements a given interface?

From stackoverflow
  • if (object is IBlah)
    

    or

    IBlah myTest = originalObject as IBlah
    
    if (myTest != null)
    
    Andrew Hare : +1 The second one is better because you will probably end up needing to cast afterward with the first one thus giving you two casts ("is" and then an explicit cast). With the second approach you only cast once.
  • For the instance:

    if (obj is IMyInterface) {}
    

    For the class:

    Check if typeof(MyClass).GetInterfaces() contains the interface.

    Constantin : if (Array.IndexOf(typeof(MyClass).GetInterfaces(), typeof(IMyInterface)) != -1) { ... }
    Lance Fisher : or: if(typeof(MyClass).GetInterfaces().Contains(typeof(IMyInterface))) {...}
  • This should work :

    MyInstace.GetType().GetInterfaces();
    

    But nice too :

    if (obj is IMyInterface)
    

    Or even (not very elegant) :

    if (obj.GetType() == typeof(IMyInterface))
    
    Jay Bazuzi : Checking for equality to typeof(IMyInterface) will always fail. Downvoted.
    Rauhotz : Right. There are no instances of an interface.
  • In addition to testing using the "is" operator, you can decorate your methods to make sure that variables passed to it implement a particular interface, like so:

    public static void BubbleSort<T>(ref IList<T> unsorted_list) where T : IComparable
    {
         //Some bubbly sorting
    }
    

    I'm not sure which version of .Net this was implemented in so it may not work in your version.

    Robert C. Barth : .net 2.0 added generics.
  • Using the is or as operators is the correct way if you know the interface type at compile time and have an instance of the type you are testing. Something that no one else seems to have mentioned is Type.IsAssignableFrom:

    if( typeof(IMyInterface).IsAssignableFrom(someOtherType) )
    {
    }
    

    I think this is much neater than looking through the array returned by GetInterfaces and has the advantage of working for classes as well.

    twk : you saved me a lot of time! thx

0 comments:

Post a Comment