Problem
Take the following type definitions into consideration:
public interface IFoo<T> : IBar<T> {}
public class Foo<T> : IFoo<T> {}
When just the mangled type is provided, how do I find out if the type Foo implements the generic interface IBarT>?
Asked by sduplooy
Solution #1
It may also be done with the following LINQ query, which uses TcKs’ answer:
bool isBar = foo.GetType().GetInterfaces().Any(x =>
x.IsGenericType &&
x.GetGenericTypeDefinition() == typeof(IBar<>));
Answered by sduplooy
Solution #2
You must walk up the inheritance tree and identify all of the interfaces for each class in the tree, then compare typeof(IBar>) with the Type result. If the interface is generic, use GetGenericTypeDefinition. It’s all a little painful, to be sure.
For further information and code, see this and these answers.
Answered by Jon Skeet
Solution #3
public interface IFoo<T> : IBar<T> {}
public class Foo : IFoo<Foo> {}
var implementedInterfaces = typeof( Foo ).GetInterfaces();
foreach( var interfaceType in implementedInterfaces ) {
if ( false == interfaceType.IsGeneric ) { continue; }
var genericType = interfaceType.GetGenericTypeDefinition();
if ( genericType == typeof( IFoo<> ) ) {
// do something !
break;
}
}
Answered by TcKs
Solution #4
As a method extension, this is referred to as a “helper method.”
public static bool Implements<I>(this Type type, I @interface) where I : class
{
if(((@interface as Type)==null) || !(@interface as Type).IsInterface)
throw new ArgumentException("Only interfaces can be 'implemented'.");
return (@interface as Type).IsAssignableFrom(type);
}
Example usage:
var testObject = new Dictionary<int, object>();
result = testObject.GetType().Implements(typeof(IDictionary<int, object>)); // true!
Answered by GenericProgrammer
Solution #5
I’m using the @GenericProgrammers extension method in a little simplified form:
public static bool Implements<TInterface>(this Type type) where TInterface : class {
var interfaceType = typeof(TInterface);
if (!interfaceType.IsInterface)
throw new InvalidOperationException("Only interfaces can be implemented.");
return (interfaceType.IsAssignableFrom(type));
}
Usage:
if (!featureType.Implements<IFeature>())
throw new InvalidCastException();
Answered by Ben Foster
Post is based on https://stackoverflow.com/questions/503263/how-to-determine-if-a-type-implements-a-specific-generic-interface-type