Does reflection in C#
offer a way to determine if some given System.Type
type models some interface?
public interface IMyInterface {}
public class MyType : IMyInterface {}
// should yield 'true'
typeof(MyType)./* ????? */MODELS_INTERFACE(IMyInterface);
IsAssignableFrom
is now moved toTypeInfo
:Modifying Jeff's answer for optimal performance (thanks to performance test by Pierre Arnaud):
To find all types that implement an interface in a given
Assembly
:I just did:
I wish I could have said
where I : interface
, butinterface
is not a generic parameter constraint option.class
is as close as it gets.Usage:
I just said
Implements
because that's more intuitive. I always getIsAssignableFrom
flip-flopped.What about
I think this is the correct release, for three reasons:
1) It uses GetInterfaces and not IsAssignableFrom, it's faster since IsAssignableFrom eventually after several checks does call GetInterfaces.
2) It iterates over the local array, so there will be no bounds checks.
3) It uses the == operator which is defined for Type, so probably is safer than the Equals method (that the Contains call, will eventually use).