.netreflection

Can you use reflection to find the name of the currently executing method?


Like the title says: Can reflection give you the name of the currently executing method.

I'm inclined to guess not, because of the Heisenberg problem. How do you call a method that will tell you the current method without changing what the current method is? But I'm hoping someone can prove me wrong there.

Update:

Final Result
I learned about MethodBase.GetCurrentMethod(). I also learned that not only can I create a stack trace, I can create only the exact frame I need if I want.

To use this inside a property, just take a .Substring(4) to remove the 'set_' or 'get_'.


Solution

  • As of .NET 4.5, you can also use [CallerMemberName].

    Example: a property setter (to answer part 2):

    protected void SetProperty<T>(T value, [CallerMemberName] string property = null)
    {
        this.propertyValues[property] = value;
        OnPropertyChanged(property);
    }
    
    public string SomeProperty
    {
        set { SetProperty(value); }
    }
    

    The compiler will supply matching string literals at call sites, so there is basically no performance overhead.