C#: automated method caller information via attributes

In C# there is a feature of the language that allows a method to receive as input parameters the member name, file path and line number of the calling method/property.

It is enough to add attributes to the method parameters receiving these values, as in the following example:

public void DoProcessing()
    TraceMessage("Something happened.");

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);

You can see that this feature can be particular useful during tracing.

The example above has been taken from Caller Information (C# and Visual Basic).

Add comment