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.
Cool. Question : In the second alternative, if the originalObject does not implement Iblah will generate some Exception?
– Guilherme de Jesus Santos
@Guilhermejsantos No, the purpose of the operators
isandasis precisely to avoid the exception. With theasor the "conversion" operation is performed or the object is not created. So it is necessary to check if it isnullnext. That is, iforiginalObjectnot implementIBlah,myTestwill be null and any attempt to access it will generate aNullReference Exceptionor some other more specialized. Theisis 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.– Maniero