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

4

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

5

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

if (object is IBlah)
     

or

IBlah myTest = originalObject as IBlah

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

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

Class

public class Mecanismo: IDisposable
{        
   public void Dispose()
   {

   }
}

Code

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");
}
//ou
if (mectype.GetInterfaces().Where(x => x.Name.Equals("IDisposable")).Any())
{
    System.Console.WriteLine("Sim, foi implementado");
}

Example Online: Ideone

    
25.08.2014 / 17:28