CallerMemberName attribute

Recently I created a WebApi where the client wanted to know what the original method name was when getting a response back.

I found a cool way to do it which .NET 4.5 offers.

The [CallerMemberName] attribute can be added as an optional parameter to any method and give you access to the calling methods name.

public class SomeClass
{
    public void SomeMethod([CallerMemberName]string memberName = "")
    {
        Console.WriteLine(memberName); //output will me name of calling method
    }
}

You can access some other useful properties too such as line number and even file path

public void TraceMessage(string message,
        [System.Runtime.CompilerServices.CallerMemberName] string memberName = "",
        [System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath = "",
        [System.Runtime.CompilerServices.CallerLineNumber] int sourceLineNumber = 0)
{
    System.Diagnostics.Trace.WriteLine("message: " + message);
    System.Diagnostics.Trace.WriteLine("member name: " + memberName);
    System.Diagnostics.Trace.WriteLine("source file path: " + sourceFilePath);
    System.Diagnostics.Trace.WriteLine("source line number: " + sourceLineNumber);
}

Leave a Reply

Your email address will not be published. Required fields are marked *