How to check if a class implements a C#interface?

Asked

Viewed 839 times

4

How to check if a class implements an interface?

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

I tried something like :

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

        }

But it didn’t happen.

2 answers

5


I found the answer in this question from Soen in the response of Robert c Barth

if (object is IBlah)

or

IBlah myTest = originalObject as IBlah

if (myTest != null)
  • 1

    Cool. Question : In the second alternative, if the originalObject does not implement Iblah will generate some Exception?

  • 3

    @Guilhermejsantos No, the purpose of the operators is and as is precisely to avoid the exception. With the as or the "conversion" operation is performed or the object is not created. So it is necessary to check if it is null next. That is, if originalObject not implement IBlah, myTest will be null and any attempt to access it will generate a NullReference Exception or some other more specialized. The is is only used if you need to know if it implements the interface but will not make a conversion, ie the object itself needs to implement it.

1

With Reflection it is easy to identify if the object of a class has been implemented with the interface IDisposable, even, one can verify 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");
}

Online Example: Ideone

Browser other questions tagged

You are not signed in. Login or sign up in order to post.