Search code examples
c#methodsstatic

Is there a way of getting the compiler to initialize a string with the enclosing method name?


Our C# codebase have several methods that create error messages that include the method's name. Can I get the compiler to statically insert the method name for me? I know I could do something with reflection, but I'd rather not.

Amongst other things, I'm seeing quite a few copy-paste errors where the exception handling from one method is copied to another, without the method name changing.

    public void Method1()
    {
        try
        {
            DoStuff();
        }
        catch (Exception e)
        {
            HandleError("Method1", details);
        }
    }

Rather than include the string "Method1" (and "Method2" up to "Methodn") is there a way of telling the compiler to insert the current method name there?


Solution

  • In NET 4.5 you can use the CallerMemberName attribute. Your HandleError method would then look like so:

    void HandleError(YourDetailsClass details,
                    [CallerMemberName] callingMethod = null)
    

    and you'd simply use

    HandleError(details);