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 this). In the generic method the type is always the base type, even when I call the method from a derived class.
I need the generic method to know that it is of the derived type and not the base type.
I am not able to change the generic method since it is from a third party app (http://razorengine.codeplex.com/ – Razor.Parse method).
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).
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 A that when called on an instance of B will call Test.WhatType and output “B”.
I hope this makes sense.
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<T>(this T obj) where T : A
{
Test.WhatType(obj);
}
}
class Test
{
public static void WhatType<T>(T obj)
{
Console.WriteLine(typeof(T).Name);
}
}
Edit: Changed method name to A.myGetType() since I hadn’t even noticed I was overloading accidentally.
N.B. Running this code outputs:
A
A
B
If I understand correctly, your problem is that
A.GetType()is binding toWhatType<A>as that is all it knows about.So you have to let class
Aknow about the derived classes.You can do this with self-referencing generic types. Something like:
then:
will bind to
WhatType<B>and so will outputB