title: System.InvalidCastException: 'Unable to cast object of type 'ClassName' to type InterfaceName'.'
body: <p>I am working on a C# application. I have a <code>ClassLibrary</code> type project which has an interface and some classes which implement this interface. Code is:</p>
  
  <pre><code>public interface IUserInterface
  {
      String GetName();
      int Function(int a, int b);
  }
  
  public class UserClass : IUserInterface
  {
      public String GetName() { return "Add"; }
      public int Function(int a, int b) { return a + b; }
  }
  
  public class UserClass1 : IUserInterface
  {
      public String GetName() { return "Add"; }
      public int Function(int a, int b) { return a + b; }
  }
  
  public class UserClass2 : IUserInterface
  {
      public String GetName() { return "Add"; }
      public int Function(int a, int b) { return a + b; }
  }
  </code></pre>
  
  <p>My requirement is that i have to find all the implementations of <code>IUserInterface</code>, create the instances of those implementations using reflection and store all these instances in a List. My code for this is:</p>
  
  <pre><code>class Program
  {
      private static List&lt;Type&gt; nameTypeDict = new List&lt;Type&gt;();
      private static List&lt;IUserInterface&gt; instances = new List&lt;IUserInterface&gt;();
      static void Main(string[] args)
      {
          Program obj = new Program();
  
          Assembly ass = Assembly.LoadFrom("ClassLibrary.dll");
          foreach (Type t in ass.GetExportedTypes())
          {
              if (t.GetInterface("IUserInterface", true) != null)
              {
                  Console.WriteLine("Found Type: {0}", t.Name);
                  nameTypeDict.Add(t);//Add to Dictonary
              }
          }
  
          foreach (var type in nameTypeDict)
          {
              var typeObject = Activator.CreateInstance(type);
  
              IUserInterface typeObj = (IUserInterface)typeObject;
  
              instances.Add(typeObject);
          }
          Console.ReadKey();
      }
  }
  </code></pre>
  
  <p>I did manage to create the instance, but gets exception at </p>
  
  <pre><code>IUserInterface typeObj = (IUserInterface)typeObject;
  </code></pre>
  
  <p>The exception is:</p>
  
  <blockquote>
    <p>System.InvalidCastException: 'Unable to cast object of type
    'ClassLibrary.UserClass' to type 'ClassLibrary.IUserInterface'.'</p>
  </blockquote>
  
  <p>How can this be resolved ? I know i am making some silly mistake but, i am unable to figure it out. The reason why i am casting it is because i have to save the instance in the <code>IUserInterface</code> type list. </p>