Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if object implements interface

What is the simplest way of testing if an object implements a given interface in C#? (Answer to this question in Java)

like image 402
JoshRivers Avatar asked Jan 04 '09 01:01

JoshRivers


People also ask

Can an object implement an interface?

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.

How do I know if a class has an interface?

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.

Which keyword validates whether a class implements 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.


2 Answers

if (object is IBlah) 

or

IBlah myTest = originalObject as IBlah  if (myTest != null) 
like image 83
Robert C. Barth Avatar answered Sep 28 '22 00:09

Robert C. Barth


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.

like image 23
Andrew Kennan Avatar answered Sep 27 '22 23:09

Andrew Kennan