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
  1. public interface IMarkable
  2.     {
  3.         void Mark();
  4.     }

 

Class that implements the interface

Code Snippet
  1. public class Marker : IMarkable
  2.     {
  3.         #region IMarkable Members
  4.  
  5.         public void Mark()
  6.         {
  7.             Console.Write("Do Mark!!");
  8.         }
  9.  
  10.         #endregion
  11.     }

 

Interface validation

Code Snippet
  1. Marker marker = new Marker();
  2.             if (marker is IMarkable)
  3.             {
  4.                 //Implements IMarkable
  5.             }

 

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
  1. public static class TypeExtension
  2.     {
  3.         public static Boolean IsImplemetationOf(this Type type, Type interfaceType)
  4.         {
  5.             Boolean returnBool = false;
  6.             Type[] interfaces = type.GetInterfaces();
  7.             for (int i = 0; i < interfaces.Length; i++)
  8.             {
  9.                 if (interfaces[i] == interfaceType)
  10.                 {
  11.                     returnBool = true;
  12.                     break;
  13.                 }
  14.             }
  15.             return returnBool;
  16.         }
  17.     }

In this manner we can make this validation when works with an instance of Type class

Code Snippet
  1. Assembly currentAssembly = Assembly.GetExecutingAssembly();
  2.             Type[] assemblyTypes = currentAssembly.GetTypes();
  3.             for (int i = 0; i < assemblyTypes.Length; i++)
  4.             {
  5.                 Type type = assemblyTypes[i];
  6.                 if (type.IsClass && type.IsImplemetationOf(typeof(IMarkable)))
  7.                 {
  8.                     //Implements IMarkable
  9.                 }
  10.             }

 

See you