title: Using reflection to cast unknown object to generic class
body: <p>I have a method which takes an object as a parameter. Within that method I walk through that objects properties with reflection. Some properties are of a generic class type. I like to read a property of that generic class property, but I cannot cast it to a generic class.</p>
  
  <pre><code>public abstract class BaseClass
  {
      public int Id { get; set; }
  }
  
  public abstract class GenericClass&lt;T&gt;: BaseClass
  {
      public string Description { get; set; }
  }
  
  public class DerivedClassA: GenericClass&lt;DerivedClassA&gt;
  {
      public string A { get; set; }
  }
  
  public class DerivedClassB: GenericClass&lt;DerivedClassB&gt;
  {
      public string B { get; set; }
  }
  
  public class ReflectingClass: BaseClass
  {
      public string Code { get; set; }
      public DerivedClassA DerA { get; set; }
      public DerivedClassB DerB { get; set; }
  }
  
  public static void Reflecting(object obj)
  {
      var t = GetType(obj)
      foreach (var pi in t.GetProperties())
      {
          if (obj.GetType().BaseType.GetGenericTypeDefinition() == typeof(GenericClass&lt;&gt;)
          {
              var genClassObjProperty = ((GenericClass&lt;T&gt;)obj).Description; // Error, cannot do this at all !!!
          }
      }
  }
  </code></pre>
  
  <p>What I want is for the code to walk to the properties and whatever the derived class actually is get the Description property of the GenericClass it is derived from. </p>
  
  <p>I am using a generic class, because elsewhere in the code I call methods by their derived class and get the proper class type without resorting to all kinds of cast and passing types. I.e:</p>
  
  <pre class="lang-cs prettyprint-override"><code>DerivedClassA.DoSomething() 
  </code></pre>
  
  <p>instead of </p>
  
  <pre class="lang-cs prettyprint-override"><code>BaseClass.DoSomething&lt;DerivedClassA&gt;()
  </code></pre>
  
  <p>or </p>
  
  <pre class="lang-cs prettyprint-override"><code>BaseClass.DoSomething(type derivedClassType)
  </code></pre>