5

Suppose I got a parent class and a child class:

public abstract class Parent
{
    public string GetParentName()
    {
        return GetType().Name;
    }
}

public class Child : Parent
{
    public string GetChildName()
    {
        return GetType().Name;
    }
}

As of current, both GetParentName() and GetChildName() will return Child.

However, in my scenario, I'd like to get the name of the class in which the method is declared.

Thus GetChildName() should return Child but GetParentName() should return Parent.

Is this by any means possible?

NOTE:

I understand that I could use GetType().BaseType.Name but this won't work since the hierarchy could be complex.

J. Doe
  • 677
  • 7
  • 20
  • `I'd like to get the name of the class in which the method is declared` i mean they are two different methods, `GetChildName` *is* declared in the child – Jonesopolis Dec 20 '16 at 17:01
  • 2
    Possible duplicate of [How do I get the calling method name and type using reflection?](http://stackoverflow.com/questions/3095696/how-do-i-get-the-calling-method-name-and-type-using-reflection) – MethodMan Dec 20 '16 at 17:01
  • 2
    You could simply return "Parent". Give us an exemple where returning a string litteral isn't appropriate. – Winter Dec 20 '16 at 17:01

1 Answers1

6

You want this, I think:

return MethodBase.GetCurrentMethod().DeclaringType.Name; 
Chris Berger
  • 557
  • 4
  • 14
  • You could also use this, if you want to be able to get the declaring type from somewhere outside of the function in question: typeof(Child).GetMembers().First(m => m.Name == "GetParentName").DeclaringType.Name – Chris Berger Dec 20 '16 at 17:09