Test if object implements interface

C#ReflectionInterface

C# Problem Overview


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

C# Solutions


Solution 1 - C#

if (object is IBlah)

or

IBlah myTest = originalObject as IBlah

if (myTest != null)

Solution 2 - C#

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 - C#

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 - C#

For the instance:

if (obj is IMyInterface) {}

For the class:

Check if typeof(MyClass).GetInterfaces() contains the interface.

Solution 5 - C#

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
}

Solution 6 - C#

This Post is a good answer.

public interface IMyInterface {}

public class MyType : IMyInterface {}

This is a simple sample:

typeof(IMyInterface).IsAssignableFrom(typeof(MyType))

or

typeof(MyType).GetInterfaces().Contains(typeof(IMyInterface))

Solution 7 - C#

What worked for me is:

Assert.IsNotNull(typeof (YourClass).GetInterfaces().SingleOrDefault(i => i == typeof (ISomeInterface)));

Solution 8 - C#

I achieved this by using the is keyword.

But also I needed a new object to use the interface properties. To achieve this you need to add the new variable after the Interface.

objectToCheck is Interface newVariableWithInterfaceProperties

.

 public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken,
            RequestHandlerDelegate<TResponse> next)
        {
            if (request is ICacheableQuery cachableRequest)
            {
             // here cachableRequest now has the interface properties.
             }
        }

Solution 9 - C#

In addition to testing using the "is" operator, you can decorate your methods to make sure that variables passed to it implement a particular interface, like so:

public static void BubbleSort<T>(ref IList<T> unsorted_list) where T : IComparable
{
     //Some bubbly sorting
}

I'm not sure which version of .Net this was implemented in so it may not work in your version.

Solution 10 - C#

Recently I tried using Andrew Kennan's answer and it didn't work for me for some reason. I used this instead and it worked (note: writing the namespace might be required).

if (typeof(someObject).GetInterface("MyNamespace.IMyInterface") != null)

Solution 11 - C#

    interface IItem
    {

    }

    class ItemImp : IItem
    {

    }

    class Program
    {
        static void Main(string[] args)
        {
            Type t = typeof(ItemImp);

            Console.WriteLine("t == typeof(IItem) -> {0}", t == typeof(IItem));
            Console.WriteLine("typeof(IItem).IsAssignableFrom(t) -> {0}", typeof(IItem).IsAssignableFrom(t));
            Console.WriteLine("t is IItem -> {0}", t is IItem);
            Console.WriteLine("new ItemImp() is IItem -> {0}", new ItemImp() is IItem);
        }
    }

// Here are outputs:
// t == typeof(IItem) -> False
// typeof(IItem).IsAssignableFrom(t) -> True
// t is IItem -> False
// new ItemImp() is IItem -> True

Solution 12 - C#

I used

Assert.IsTrue(myObject is ImyInterface);

for a test in my unit test which tests that myObject is an object which has implemented my interface ImyInterface.

Solution 13 - C#

I had a situation where I was passing a variable to a method and wasn't sure if it was going to be an interface or an object.

The goals were:

  1. If item is an interface, instantiate an object based on that interface with the interface being a parameter in the constructor call.
  2. If the item is an object, return a null since the constuctor for my calls are expecting an interface and I didn't want the code to tank.

I achieved this with the following:

    if(!typeof(T).IsClass)
    {
       // If your constructor needs arguments...
       object[] args = new object[] { my_constructor_param };
       return (T)Activator.CreateInstance(typeof(T), args, null);
    }
    else
       return default(T);

Solution 14 - C#

This should work :

MyInstace.GetType().GetInterfaces();

But nice too :

if (obj is IMyInterface)

Or even (not very elegant) :

if (obj.GetType() == typeof(IMyInterface))

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJoshRiversView Question on Stackoverflow
Solution 1 - C#Robert C. BarthView Answer on Stackoverflow
Solution 2 - C#Andrew KennanView Answer on Stackoverflow
Solution 3 - C#Martin SchneiderView Answer on Stackoverflow
Solution 4 - C#RauhotzView Answer on Stackoverflow
Solution 5 - C#famousgarkinView Answer on Stackoverflow
Solution 6 - C#eliasetmView Answer on Stackoverflow
Solution 7 - C#Dutchman078View Answer on Stackoverflow
Solution 8 - C#maviView Answer on Stackoverflow
Solution 9 - C#jamesmillerioView Answer on Stackoverflow
Solution 10 - C#jahuView Answer on Stackoverflow
Solution 11 - C#Guosheng ChenView Answer on Stackoverflow
Solution 12 - C#iamrcwView Answer on Stackoverflow
Solution 13 - C#Anthony TristanView Answer on Stackoverflow
Solution 14 - C#Yoann. BView Answer on Stackoverflow