Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get inherited caller type name in base static class

i have:

class parent
{
    public static string GetTypeName()
    { 
        /* here i want to get the caller's type
        So child.GetTypeName() should display "child" */
    }            
}     

class child : parent { }

static void Main()
{
    Console.WriteLine(child.GetTypeName());
}

Is it possible somehow to get the caller's type in base class?

like image 445
klm_ Avatar asked Sep 02 '25 05:09

klm_


2 Answers

It is not possible unless you pass the caller to the method (as an argument) or walk the stack frame to get the caller.

The compiler substitutes parent for child when calling parent's static methods through the child type. For example, here's the IL code for a call to child.GetTypeName():

IL_0002:  call   class [mscorlib]System.Type Tests.Program/parent::GetTypeName()
like image 64
Jeff Sternal Avatar answered Sep 04 '25 23:09

Jeff Sternal


I believe this.GetType() will do this. But can't check at the moment.

(assuming you want the child's type in the parent's method.)

like image 34
Massif Avatar answered Sep 05 '25 00:09

Massif