Is really simple know if any type implements an interface in the traditional way we can use the “is” keyword to know if the class instance implements the interface, by instance
Interface
Code Snippet
- public interface IMarkable
- {
- void Mark();
- }
Class that implements the interface
Code Snippet
- public class Marker : IMarkable
- {
- #region IMarkable Members
-
- public void Mark()
- {
- Console.Write("Do Mark!!");
- }
-
- #endregion
- }
Interface validation
Code Snippet
- Marker marker = new Marker();
- if (marker is IMarkable)
- {
- //Implements IMarkable
- }
But if are we working with an instance of Type class, not exists a built-in method to determinate if the type implements the interface
A simple way to get this is extend the Type class using the Extensions Method feature, we can write something like this
Code Snippet
- public static class TypeExtension
- {
- public static Boolean IsImplemetationOf(this Type type, Type interfaceType)
- {
- Boolean returnBool = false;
- Type[] interfaces = type.GetInterfaces();
- for (int i = 0; i < interfaces.Length; i++)
- {
- if (interfaces[i] == interfaceType)
- {
- returnBool = true;
- break;
- }
- }
- return returnBool;
- }
- }
In this manner we can make this validation when works with an instance of Type class
Code Snippet
- Assembly currentAssembly = Assembly.GetExecutingAssembly();
- Type[] assemblyTypes = currentAssembly.GetTypes();
- for (int i = 0; i < assemblyTypes.Length; i++)
- {
- Type type = assemblyTypes[i];
- if (type.IsClass && type.IsImplemetationOf(typeof(IMarkable)))
- {
- //Implements IMarkable
- }
- }
See you