Suppose I have the following:
class Parent
{
public static string NameCalledOn()
{
Type t = ???;
return t.Name;
}
}
class Child : Parent
{
}
What could go in place of ??? to determine which class (Parent or Child) was specified in a call to NameCalledOn? E.g.:
Parent.NameCalledOn()
should return "Parent" and Child.NameCalledOn()
should return "Child".
I saw mention of MethodBase.GetCurrentMethod().DeclaringType
but that returns "Parent" for both.
Why I would want to do this: The URL-building helpers in ASP.NET MVC require the name of the controller and the name of the method. I don't want to use literal strings (typo-prone), and using nameof(MyController)
doesn't work because it expects the name of the controller without the "Controller" suffix. The shortest way I can think of is to create a get-only "Name" property on my base controller which determines which actual controller class the call was made on and returns its name with "Controller" chopped off.
Note that I'm using .NET Core 3.1, so this can include features from any C# version 3.1 supports.