//The following is a code example for being able to check whether an object is derived from or
//implements a generic class or interface.
//for more info see: http://blog.aggregatedintelligence.com/2013/02/cdetermining-if-object-implements-or.html
namespace ConsoleApplication1
{
using System;
using System.Linq;
class Program
{
static void Main(string[] args)
{
MyInt myInt = new MyInt();
MyInterfacedInt myIInt = new MyInterfacedInt();
"Using the \\"is\\" keyword".Dump();
(myInt is MyInt).Dump();//true
(myIInt is MyInterfacedInt).Dump();//true;
(myInt is MyGenericClass<int>).Dump();//true
(myIInt is IMyGenericInterface<int>).Dump();//true;
//Will not compile
//(myInt is MyGenericClass<>).Dump();
//(myInt is IMyGenericInterface<>).Dump();
"Using IsDerivedOrImplementedFrom".Dump();
myInt.IsDerivedOrImplementedFrom(typeof(MyInt)).Dump(); //true
myIInt.IsDerivedOrImplementedFrom(typeof(MyInterfacedInt)).Dump();//true
myInt.IsDerivedOrImplementedFrom(typeof(MyGenericClass<int>)).Dump();//true
myIInt.IsDerivedOrImplementedFrom(typeof(IMyGenericInterface<int>)).Dump();//true
myInt.IsDerivedOrImplementedFrom(typeof(MyGenericClass<>)).Dump();//true
myIInt.IsDerivedOrImplementedFrom(typeof(IMyGenericInterface<>)).Dump();//true
"Negative tests Using IsDerivedOrImplementedFrom".Dump();
myInt.IsDerivedOrImplementedFrom(typeof(MyInterfacedInt)).Dump(); //false
myIInt.IsDerivedOrImplementedFrom(typeof(MyInt)).Dump();//false
myInt.IsDerivedOrImplementedFrom(typeof(MyGenericClass<string>)).Dump();//false
myIInt.IsDerivedOrImplementedFrom(typeof(IMyGenericInterface<string>)).Dump();//false
myInt.IsDerivedOrImplementedFrom(typeof(IMyGenericInterface<>)).Dump();//false
myIInt.IsDerivedOrImplementedFrom(typeof(MyGenericClass<>)).Dump();//false
Console.ReadLine();
}
}
public abstract class MyGenericClass<T>
{
}
public interface IMyGenericInterface<T>
{
}
public class MyInt : MyGenericClass<int>
{
}
public class MyInterfacedInt : IMyGenericInterface<int>
{
}
public static class ReflectionHelper
{
public static void Dump(this object objToDump)
{
if (objToDump != null)
Console.WriteLine(objToDump);
}
public static bool IsDerivedOrImplementedFrom<T>(this T objectToCheck, Type parentType) where T : class
{
if (objectToCheck == null)
return false;
if (parentType.IsInstanceOfType(objectToCheck))
return true;
bool checkingInterfaces = parentType.IsInterface;
Type toCheck = objectToCheck.GetType();
while (toCheck != null && toCheck != typeof(object))
{
var cur = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck;
if (checkingInterfaces)
{
bool implementsParentInterface = toCheck.GetInterfaces()
.Any(ci =>
{
return ci.IsGenericType ? ci.GetGenericTypeDefinition() == parentType :
ci == parentType;
});
if (implementsParentInterface)
return true;
}
else
{
if (parentType == cur)
{
return true;
}
}
toCheck = toCheck.BaseType;
}
return false;
}
}
}