title: Dynamic cast using Type of object C#
body: <p>I have one abstract class named A, and other classes (B, C, D, E, ...) that implements A </p>
  
  <p>I also have a list of A objects.<br>
  I'd like to be able to cast dynamicly each of the object in that list to their "base" type (ie B, C, D, ...) to be able to call their constructor in an other method.</p>
  
  <p>Here is what I have done for now :</p>
  
  <pre><code>abstract class A { }
  class B : A { }
  class C : A { }
  class D : A { }
  class E : A { }
  // ... 
  
  class Program
  {
      static void Main(string[] args)
      {
          List&lt;A&gt; list = new List&lt;A&gt; { new B(), new C(), new D(), new E() };
          // ...
  
          foreach (A item in list)
          {
              A obj  = foo(item);
          }
      }
  
      public static A foo(A obj)
      {
          if (obj.GetType() == typeof(B))
          {
              return bar((B)obj);
          }
          else if (obj.GetType() == typeof(C))
          {
              return bar((C)obj);
          }
          // ... same for D, E, ...
          return null;
      }
  
      public static T bar&lt;T&gt;(T obj) where T : class, new()
      {
          // To use the constructor, I can't have here an abstract class.
          T newObj = new T();
          return newObj;
      }
  </code></pre>
  
  <p>It works, but I'd like to find an other way but to test for each class that implements A if their type equals the type of my object, and cast it afterwards.</p>
  
  <p>I have nearly 15 classes like B, C, D, ... and I might have more. 
  In order to have something simple, clear and maintainable, I'd like to avoid this methods, and the 15+ "if(...) else(...)".</p>
  
  <p>Do you see a way to do so ?</p>