Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get class type?

Given

public class A
{
    public static void Foo()
    {
        // get typeof(B)
    }
}

public class B : A
{

}

Is it possible for B.Foo() to get typeof(B) in .NET 4? Note that Foo is static.

like image 695
mpen Avatar asked Sep 24 '26 02:09

mpen


2 Answers

There is no difference between A.Foo() and B.Foo(). The compiler emits a call to A.Foo() in both cases. So, no, there is no way to detect if Foo was called as A.Foo() or B.Foo().

like image 96
dtb Avatar answered Sep 26 '26 19:09

dtb


Unfortunately this isn't possible, as dtb explains.

One alternative is to make A generic like so:

public class A<T>
{
    public static void Foo()
    {
        // use typeof(T)
    }
}

public class B : A<B>
{
}

Another possibility is to make the A.Foo method generic and then provide stub methods in the derived types that then call the "base" iplementation.

I'm not keen on this pattern. It's probably only worthwhile if you absolutely need to keep the B.Foo calling convention, you can't make A itself generic, and you have lots of shared logic inside A.Foo that you don't want to repeat in your derived types.

public class A
{
    protected static void Foo<T>()
    {
        // use typeof(T)
    }
}

public class B : A
{
    public static void Foo()
    {
        A.Foo<B>();
    }
}
like image 33
LukeH Avatar answered Sep 26 '26 20:09

LukeH



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!