If we have an object of a type, we can easily check if that object implements a particular type by using is operator.

 

if(o is IExample)

Console.WriteLine("Yes");

 

Here the If statement will evaluate to true if the object o implements the interface IExample or the object is a derived object of IExample.

 

However, we cannot use is operator if all we got is a type and we want to find whether that type implements a particular interface.

 

Type.IsAssignableFrom()

The System.Type class has an IsAssignableFrom() method which does exactly what we want. The IsAssignableFrom() method takes a type as its argument and returns true if the object of the provided type can be assigned to a variable of the current type. See the following example:

 

interface IExample

{

 void Do();

}

class Example : IExample

{

 

    #region IExample Members

 

    public void Do()

    {

        throw new Exception("The method or operation is not implemented.");

    }

 

    #endregion

}

 

Here we are declaring an interface IExample and a class Example which implements the IExample interface. Now let us see how we can check that the type Example implements IExample interface.

 

if(typeof(IExample).IsAssignableFrom(typeof(Example)))

Console.WriteLine("Yes");

 

This will output “yes” to the console as the interface IExample is implemented by class Example class. For more information on Type.IsAssignableFrom() method, visit this MSDN page.

 

Happy coding!