How to check whether a class implements an interface
If we work with objects, it is not difficult to determine if a class implements an interface. This can be done with the is keyword.
But it gets difficult if we work with reflection. The type object of a class, contains a method called IsSubclassOf, but if we try to use it with an interface it returns false in any case and if we try to get all implemented interfaces and search the one we need, we’ll have to much work with this simple issue.
So how can we do this in a very easy way? I found the answer here. To shorten this long description, I’ll give you the answer right here:
typeof(IFoo).IsAssignableFrom(bar.GetType()); typeof(IFoo).IsAssignableFrom(typeof(BarClass));
The method IsAssignableFrom checks whether the type can be assigned from another. It takes a type objects as an argument an returns true if the type can be assigned.
No comments yet.