Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the name of the declaring class?

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.

like image 845
J. Doe Avatar asked Dec 20 '16 16:12

J. Doe


1 Answers

You want this, I think:

return MethodBase.GetCurrentMethod().DeclaringType.Name; 
like image 137
Chris Berger Avatar answered Oct 05 '22 22:10

Chris Berger