Skip to content
Amal Hashim
All posts
Article

C# 5.0 - Caller Information

Use the CallerMemberName, CallerFilePath and CallerLineNumber attributes in C# 5 to log where a method was called from.

1 min read#.NET#C##Visual Studio

Caller information is new in C# 5 and works directly in Visual Studio 2012. It is a set of attributes that give a method information about its caller: the source file path, the line number and the member name. This is useful when you debug or trace application issues.

The attributes

  • CallerFilePathAttribute - a string with the path of the source file, captured at compile time.
  • CallerLineNumberAttribute - an integer with the line number where the method is invoked.
  • CallerMemberNameAttribute - a string with the name of the calling method or property.

These attributes can only be used on optional parameters, so each one needs a default value. A typical logging method looks like this:

csharp
//...
Log("Log this");
//...

public void Log(string messageToLog,
        [CallerMemberName] string memberName = "",
        [CallerFilePath] string filePath = "",
        [CallerLineNumber] int lineNumber = 0)
{
    // Log the details
}

Include these using statements:

csharp
using System.Runtime.CompilerServices;
using System.Diagnostics;

Example

If Log("Log this") is called from a method named SaveOrder on line 42 of Orders.cs, the parameters arrive as memberName = "SaveOrder", the full path of Orders.cs, and lineNumber = 42.