title: typeof this in virtual methods called from derived class
body: <p>I have found myself in a situation where I have a method on a base class which makes a call to a generic method passing itself as a parameter (via <code>this</code>). In the generic method the type is always the base type, even when I call the method from a derived class.</p>
  
  <p>I need the generic method to know that it is of the derived type and not the base type.</p>
  
  <p>I am not able to change the generic method since it is from a third party app (http://razorengine.codeplex.com/ - <code>Razor.Parse</code> method).</p>
  
  <p>I have found that if I define the method as a generic extension method restricted to types inheriting from my base class that calling this then works but it seems messy to use extension methods for this purpose (though if this is correct usage I'd be happy to hear that). What I am wondering if there is some trick I can use that will convert "this" to the type of the derived object before it gets called (maybe using generics still).</p>
  
  <p>I have included a simplified program below that should be self contained (I'm running it in LINQPad for personal ease). Essentially I want a method defined on <code>A</code> that when called on an instance of <code>B</code> will call <code>Test.WhatType</code> and output "B".</p>
  
  <p>I hope this makes sense.</p>
  
  <pre><code>void Main()
  {
      var bar = new B();
      bar.myGetType();
      bar.ExtGetType();
  }
  
  class A
  {
      public virtual void myGetType()
      {
          Test.WhatType(this);
          this.ExtGetType();
      }
  }
  
  class B : A {}
  
  static class ext
  {
      public static void ExtGetType&lt;T&gt;(this T obj) where T : A
      {
          Test.WhatType(obj);
      }
  }
  
  class Test
  {
      public static void WhatType&lt;T&gt;(T obj)
      {
          Console.WriteLine(typeof(T).Name);
      }
  }
  </code></pre>
  
  <p><strong>Edit:</strong> Changed method name to <code>A.myGetType()</code> since I hadn't even noticed I was overloading accidentally.</p>
  
  <p>N.B. Running this code outputs:</p>
  
  <pre><code>A
  A
  B
  </code></pre>