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);
As someone else already mentioned: Benjamin Apr 10 '13 at 22:21"
Well, another way around is just to create a short extension method that fulfills, to some extent, the "most usual" way of thinking (and agreed this is a very little personal choice to make it slightly "more natural" based on one's preferences):
And why not going a bit more generic (well not sure if it is really that interesting, well I assume I'm just passing another pinch of 'syntaxing' sugar):
I think it might be much more natural that way, but once again just a matter of very personal opinions:
A correct answer is
However,
might return a wrong result, as the following code shows with string and IConvertible:
Results:
or
what about
?
You have a few choices off the top of my head
typeof(IMyInterface).IsAssignableFrom(typeof(MyType))
typeof(MyType).GetInterfaces().Contains(typeof(IMyInterface))
For a generic interface, it’s a bit different.
Use
Type.IsAssignableFrom
: