1

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.

user221592
  • 361
  • 1
  • 10
  • 2
    What about writing an extension method like `public static string NameCalledOn(this Parent obj)` in different class and to get the type use `obj.GetType()`? – user1672994 Dec 22 '20 at 05:21
  • You might be interested to see this question: https://stackoverflow.com/questions/2081612/net-determine-the-type-of-this-class-in-its-static-method especially the answer by Jon Skeet. Do you absolutely have to make this method static, by the way? – default locale Dec 22 '20 at 05:22
  • You need to rethink your problem. This is not a situation you should be in. – TheGeneral Dec 22 '20 at 05:50
  • For strongly typed controller and action names, take a look at [T4MVC/R4MVC](https://github.com/T4MVC/R4MVC). – madreflection Dec 22 '20 at 06:22

2 Answers2

0

Static's are not meant for usual inheritance rules of C#.

Making the method NameCalledOn() instance method will work the best. There is no harm, all methods are loaded only once in memory for all instances. Data members for each instance consume separate memory but methods do not.

samiksc
  • 167
  • 10
0

Static method is not overridable, so the only way to achieve it is overwrting.

class Parent
{
    public static string NameCalledOn()
    {
        return "Parent";
    }
}

class Child : Parent
{
    public new static string NameCalledOn()
    {
        return "Child";
    }
}
shingo
  • 18,436
  • 5
  • 23
  • 42