Test if object implements interface
Solution 1
if (object is IBlah)
or
IBlah myTest = originalObject as IBlah
if (myTest != null)
Solution 2
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.
Solution 3
If you want to use the typecasted object after the check:
Since C# 7.0:
if (obj is IMyInterface myObj)
This is the same as
IMyInterface myObj = obj as IMyInterface;
if (myObj != null)
See .NET Docs: Pattern matching overview
Solution 4
For the instance:
if (obj is IMyInterface) {}
For the class:
Check if typeof(MyClass).GetInterfaces()
contains the interface.
Solution 5
A variation on @AndrewKennan's answer I ended up using recently for types obtained at runtime:
if (serviceType.IsInstanceOfType(service))
{
// 'service' does implement the 'serviceType' type
}
JoshRivers
Updated on October 19, 2021Comments
-
JoshRivers over 2 years
What is the simplest way of testing if an object implements a given interface in C#? (Answer to this question in Java)