Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current class at runtime in a static method?

How can I get the type (not a name string, but a type itself) of the current class, in a static method of an abstract class?

using System.Reflection; // I'll need it, right?

public abstract class AbstractClass {

    private static void Method() {

        // I want to get CurrentClass type here

    }

}

public class CurrentClass : AbstractClass {

    public void DoStuff() {

        Method(); // Here I'm calling it

    }

}

This question is very similar to this one:

How to get the current class name at runtime?

However, I want to get this information from inside the static method.

like image 920
Max Yankov Avatar asked Aug 10 '26 02:08

Max Yankov


2 Answers

public abstract class AbstractClass
{
    protected static void Method<T>() where T : AbstractClass
    {
        Type t = typeof (T);

    }
}

public class CurrentClass : AbstractClass
{

    public void DoStuff()
    {
        Method<CurrentClass>(); // Here I'm calling it
    }

}

You can gain access to the derived type from the static method simply by passing the type as a generic type argument to the base class.

like image 184
User 12345678 Avatar answered Aug 11 '26 16:08

User 12345678


I think you will have to either pass it in like the other suggestion or create a stack frame, I believe if you put an entire stack trace together though it can be expensive.

See http://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace.aspx

like image 43
Ian Avatar answered Aug 11 '26 15:08

Ian