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
is
andas
is precisely to avoid the exception. With theas
or the "conversion" operation is performed or the object is not created. So it is necessary to check if it isnull
next. That is, iforiginalObject
not implementIBlah
,myTest
will be null and any attempt to access it will generate aNullReference Exception
or some other more specialized. Theis
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.– Maniero