4

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?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
klm_
  • 1,199
  • 1
  • 10
  • 26
  • What do you mean by 'get caller's type in base class?' Get the name of the base type from the inheriting type, right? – Grant Thomas Jan 19 '11 at 14:34
  • Not really an answer, but you can it by looking up the stackframes / stacktrace, but this is a very hacky approach, and not recommended. Var better to use a virtual method or `GetType()` – Marc Gravell Jan 19 '11 at 14:36
  • noo, in main() it should display : "child". – klm_ Jan 19 '11 at 14:36
  • or the name of the inheriting type, inside a method on the base type? – Massif Jan 19 '11 at 14:36
  • Ahhh, now I see what you mean... just because is dawned on me - and no, to answer your question, at least not easily at all. – Grant Thomas Jan 19 '11 at 14:37
  • Marc Gravell - yes, I found that hack, not like it. I think there is no good slution,but maybe somebody here, on SO knows more :) – klm_ Jan 19 '11 at 14:37
  • What was wrong with the regular `GetType()`? I assume you're trying to do something more in your code than you're showing us here? – Cody Gray - on strike Jan 19 '11 at 14:38
  • @klm_: Why can't you use `typeof(child).Name`? – max Jan 19 '11 at 14:38
  • @max: because `Parent` is unaware of `Child` in this sense, and this method can be called publicly, so the caller may not be a `Child`. – Grant Thomas Jan 19 '11 at 14:39
  • @Mr. Disappointment: but caller will always explicitly know about `Child` and can write `typeof(Child)` istead of `child.GetTypeName()`. – max Jan 19 '11 at 14:42
  • @Cody Gray: this is all i need. frankly – klm_ Jan 19 '11 at 14:45
  • @max: However, the question states: 'get the caller's type in base class', which implied that if type `Grandchild` called the method it would print the type name of such. Regardless, seems he figured out what was needed. – Grant Thomas Jan 19 '11 at 15:59

2 Answers2

9

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()
Jeff Sternal
  • 47,787
  • 8
  • 93
  • 120
1

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.)

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Massif
  • 4,327
  • 23
  • 25