What is the simplest way of testing if an object implements a given interface in C#? (Answer to this question in Java)
If you define a reference variable whose type is an interface, any object you assign to it must be an instance of a class that implements the interface. By casting object1 to a Relatable type, it can invoke the isLargerThan method.
isInterface() method The isArray() method of the Class class is used to check whether a class is an interface or not. This method returns true if the given class is an interface. Otherwise, the method returns false , indicating that the given class is not an interface.
With the aim to make the code robust, i would like to check that the class implements the interface before instantiation / casting. I would like the the keyword 'instanceof' to verify a class implements an interface, as i understand it, it only verifies class type.
if (object is IBlah)
or
IBlah myTest = originalObject as IBlah if (myTest != null)
Using the is
or as
operators is the correct way if you know the interface type at compile time and have an instance of the type you are testing. Something that no one else seems to have mentioned is Type.IsAssignableFrom
:
if( typeof(IMyInterface).IsAssignableFrom(someOtherType) ) { }
I think this is much neater than looking through the array returned by GetInterfaces
and has the advantage of working for classes as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With