Search code examples
c#postsharp

How to obtain method name in the original method when using PostSharp?


I'm using Visual Studio 2010, .NET 3.5 and PostSharp 3.1.33. When I execute this code

[MyInterceptorAspect]
public void Send(string msg)
{
    Console.WriteLine(MethodBase.GetCurrentMethod().Name);
}

it prints <Send>z__OriginalMethod, but I want it to print just Send. Is it possible at all? (NB: MyInterceptorAspect extends MethodInterceptionAspect and it works flawlessly, concrete implementation is just not important for this problem)


Solution

  • Since PostSharp changes your methods after they've been compiled, one solution is to resolve it at compile time, rather than runtime.

    string CurrentMethod([CallerMemberName] string caller = null)
    {
        return caller;
    }
    
    Console.WriteLine(CurrentMethod());
    

    Alternatively, you could just search the 'mangled' name using a regex, to find the original name.

    string GetOriginalName(string mangled)
    {
        return new Regex(@"\w+").Match(mangled).Value;
    }