How to check if a class implements an interface, in C #?


How to check if a class implements an interface?

For example, I want to include an if that checks whether an object is of type IDisposable. How to do?

I tried something like:

        MinhaClasse meuObjeto = new MinhaClasse();
        if (typeof(meuObjeto) == IDisposable)


But it did not roll.

asked by anonymous 25.08.2014 / 15:58

2 answers


I found the answer in this SOEn query in the answer to Robert c barth

if (object is IBlah)


IBlah myTest = originalObject as IBlah

if (myTest != null)
25.08.2014 / 16:03

With Reflection it is easy to identify whether the object of a class was implemented with interface IDisposable , inclusive, you can check if there are more implementations in this way


public class Mecanismo: IDisposable
   public void Dispose()



Mecanismo mecanismo = new Mecanismo();
Type mectype = mecanismo.GetType();
var c = mectype.GetInterface("System.IDisposable"); //forma direta
if (c != null)
    System.Console.WriteLine("Sim, foi implementado");
if (mectype.GetInterfaces().Where(x => x.Name.Equals("IDisposable")).Any())
    System.Console.WriteLine("Sim, foi implementado");

Example Online: Ideone

25.08.2014 / 17:28