Sometimes it is useful to check whether a class (or its instance) implements certain interface. I found a good thread today discussing the issue:
How to determine base interface??? - .NET C#
If you are too busy (well, or too lazy) to dig the answer out of the long page, here is the solution:
typeof(IFoo).IsAssignableFrom(bar.GetType());
typeof(IFoo).IsAssignableFrom(typeof(BarClass));The Type.IsAssignableFrom() method check whether a type can be assigned from another. It takes a System.Type object as argument, so if you are given a class or an instance of a class, you can use the typeof operator or the Object.GetType() method to get the corresponding System.Type object respectively. The MSDN has a clear definition of the returned value of the IsAssignableFrom() method:
Return ValueAs you may have noticed, the IsAssignableForm() method can be applied to all System.Type object, so you can definitely use it to determine whether a class is derived (directly or indirectly) from another. But the case could be more complicated. When you have an interface and a class, the only possible relation is the class (or any class in its class hierarchy) implements the interface. But when you have two classes and try to find out their relation, one could be either the same as, the base or a derivative of another. For the first two case the IsAssignableForm() method returns a true value. Instead of explicitly checking whether two classes being the same, you may use the Type.isSubClassOf() method instead:
Type: System.Boolean
true if c and the current Type represent the same type, or if the current Type is in the inheritance hierarchy of c, or if the current Type is an interface that c implements, or if c is a generic type parameter and the current Type represents one of the constraints of c. false if none of these conditions are true, or if c is a null reference.
typeof(FooClass).isSubClassOf(typeof(BarClass));Let me use the following examples as a summary:
interface I { /* ... */ }
class A : I { /* ... */ }
class B : A { /* ... */ }
/* something */
Console.WriteLine(typeof(A).isAssignableFrom(typeof(I))); // false
Console.WriteLine(typeof(A).isSubClassOf(typeof(I))); // false
Console.WriteLine(typeof(I).isAssignableFrom(typeof(A))); // true
Console.WriteLine(typeof(I).isAssignableFrom(typeof(B))); // true
Console.WriteLine(typeof(B).isSubClassOf(typeof(I))); // false
Console.WriteLine(typeof(A).isAssignableFrom(typeof(A))); // true
Console.WriteLine(typeof(A).isSubClassof(typeof(A))); // false
Console.WriteLine(typeof(A).isAssignableFrom(typeof(B))); // true
Console.WriteLine(typeof(A).isSubClassof(typeof(B))); // false
Console.WriteLine(typeof(B).isAssignableFrom(typeof(A))); // false
Console.WriteLine(typeof(B).isSubClassof(typeof(A))); // true
/* something else */

