To test if object implements interface in C# - Pattern matching overview

Is there anyway of testing if an object implements a given interface in C#?

Solution:



Solution 1:
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 2:
FYI: This is previous version of using and testing

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.



Inspired by: Stackoverflow