What is the simplest way of testing if an object implements a given interface in C#? (Answer to this question in Java)
14 Answers
if (object is IBlah)
or
IBlah myTest = originalObject as IBlah
if (myTest != null)

- 22,687
- 6
- 45
- 52
-
97+1 The second one is better because you will probably end up needing to cast afterward with the first one thus giving you two casts ("is" and then an explicit cast). With the second approach you only cast once. – Andrew Hare Jan 04 '09 at 06:02
-
56@Andrew: +1; Time again for the [link](http://www.boyet.com/Articles/DoubleCastingAntiPattern.html) to the classic Double-Casting AntiPattern blog post by [Julian M Bucknall](http://www.boyet.com). – Jeroen Wiert Pluimers Mar 17 '11 at 12:27
-
1Optimisation probably won't have you cast twice in the first case ? – BuZz Jul 19 '13 at 10:55
-
1@Joreen, that link misses one point if you are working with a structure you can't use "as" because it wont hold a null which is what the "as" tries to return, in that case you have to go through a nullable class like int?, though not an issue if your only working at the interface level as they are always reference types – MikeT Sep 30 '13 at 13:40
-
@Jeroen: I think, performance is not a strong argument here. Probably time again for the [link](http://c2.com/cgi/wiki?PrematureOptimization) to the Premature Optimization AntiPattern article. – uebe Nov 09 '15 at 09:00
-
The second method has a new advantage in C# 6.0. `(originalObject as IBlah)?.FooProperty` will return `FooProperty` if the original object is `IBlah`, or it'll return a null. One-liner access to a property, if that's all you need from the class. On the downside, it'd be too easy to have multiple lines like that if you aren't careful in development. – saluce Jun 10 '16 at 16:48
-
76Since C# 6.0: `if (object is IBlah iblah) { iblah.SomeMethod(); }` – Knelis Jun 26 '17 at 09:40
-
To advocate for the first method, it is very linq friendly, for filtering ala. list.Select(e => e is IBlah) – Henrik Jun 27 '17 at 13:00
-
Since C#7: `IBlah myListTest= originalObject as IBlah ?? some_code`. Some_code can include any of the following `null` OR `throw new ArgumentNullException("originalObject")` OR `new List
– Paulustrious Jul 23 '17 at 16:44 -
This doesnt work for generic interfaces without defining the interface, ie `object is IBlah<>` doesnt compile. For this Andrews answer below works better – Ulrik Apr 25 '18 at 06:24
-
1@Knelis, do you have documentation supporting that pattern matching works in C# 6? Microsoft's [documentation on the subject](https://learn.microsoft.com/en-us/dotnet/csharp/pattern-matching) suggests it's C# 7 and on, not 6. – Muhammad Abdul-Rahim May 01 '18 at 17:29
-
How is work when the interface lass is generic? but you dont know the the type os it. – György Gulyás Dec 11 '18 at 14:48
-
@Knelis: It's now 2021, and I've been living my life for 4 years not knowing that. That's crazy! – Bennyboy1973 May 13 '21 at 07:44
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.

- 13,947
- 3
- 24
- 33
-
I'm trying to determine if a type implements some instantiation of IList. I'm using "typeof(IList<>).IsAssignableFrom(someType)" but that isn't working. – KeyboardDrummer Sep 19 '11 at 12:31
-
3You might be better off asking this in another question. If someType is the type of the list elements you could need typeof(IList<>).MakeGenericType(someType). If someType is the list type you should look at Type.GetGenericArguments and Type.GetGenericTypeDefinition. – Andrew Kennan Sep 20 '11 at 02:39
-
I use this for type checking in a plugin system. It can be used in situations where an instance of the object does not yet exist. But I use both this style and Robert's depending on what I am doing so I up voted both ways. – James Mar 23 '12 at 11:56
-
This is an older comment, but to answer @Steenreem's question, use `typeof(IList).IsAssignableFrom(someType)`, without the `<>`. – saluce Feb 14 '13 at 16:38
-
1This method even works with conversion operators and if TypeConverters are involved – Harald Coppoolse Aug 05 '14 at 07:45
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

- 14,263
- 7
- 55
- 58
For the instance:
if (obj is IMyInterface) {}
For the class:
Check if typeof(MyClass).GetInterfaces()
contains the interface.

- 45,157
- 15
- 111
- 168

- 7,914
- 6
- 40
- 44
-
1if (Array.IndexOf(typeof(MyClass).GetInterfaces(), typeof(IMyInterface)) != -1) { ... } – Constantin Jan 04 '09 at 03:07
-
2or: if(typeof(MyClass).GetInterfaces().Contains(typeof(IMyInterface))) {...} – Lance Fisher Jan 04 '09 at 03:12
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
}

- 13,687
- 5
- 58
- 74
What worked for me is:
Assert.IsNotNull(typeof (YourClass).GetInterfaces().SingleOrDefault(i => i == typeof (ISomeInterface)));

- 91
- 1
- 8
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.
}
}

- 1,074
- 2
- 15
- 29
-
1From all answers this seem the perfect combination between clarity and cleaner code. Liked it, thanks! It would be also nice to have performance metrics for this. – Machado Jan 20 '22 at 18:08
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.

- 3,154
- 4
- 27
- 32
-
This is the **only** _compile-time_ check in this thread, thanks. – Dustin Malone Jan 19 '19 at 20:04
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

- 21
- 2
-
3If responding to an old question, you should explain why your answer is more relevant than the answers previously submitted. An example would be noting that an update in C# allows x to be accomplished now where it was more complicated in the past. – Beems Oct 19 '21 at 03:18
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)

- 5,427
- 3
- 37
- 64
-
3If you end up going this route, I'm not a fan of magic strings, so I'd at minimum change this to be typeof(IMyInterface).Name instead of "MyNamespace.IMyInterface". Helps to make it name refactoring proof as a bonus. – greyalien007 May 06 '15 at 19:01
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.

- 31
- 5
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:
- If item is an interface, instantiate an object based on that interface with the interface being a parameter in the constructor call.
- 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);

- 59
- 1
- 4
This should work :
MyInstace.GetType().GetInterfaces();
But nice too :
if (obj is IMyInterface)
Or even (not very elegant) :
if (obj.GetType() == typeof(IMyInterface))

- 11,075
- 19
- 69
- 111
-
10Checking for equality to typeof(IMyInterface) will always fail. Downvoted. – Jay Bazuzi Jan 04 '09 at 02:07
-