What is the simplest way of testing if an object implements a given interface in C#? (Answer to this question in Java)
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 with is # Type pattern
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.
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.
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:
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);
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)
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
}