Skip to content

Caller info attributes C# 5.0code reduction

Provide parameter attributes to capture information about the caller of a method.

Being able to report where a method is called from is very useful when performing logging or tracing however it is intrusive and error-prone to manually add this information yourself.

C# 5.0 adds attributes which include:

  • CallerMemberName for receiving the name of the method that called this one
  • CallerFilePath for the name of the full path of the source file that called this method
  • CallerLineNumber for the line number within that source file

Code

C#
Customer LoadCustomer(Guid id)
{
    Log("Querying for customer " + id);
    return db.Customers.FirstOrDefault(c => c.id == id);
}

void Log(string message, [CallerMemberName] string memberName = "") {
    logger.Log(LogLevel.Info, message, memberName);
}
C#
Customer LoadCustomer(Guid id)
{
    Log("Querying for customer " + id, "LoadCustomer");
    return db.Customers.FirstOrDefault(c => c.id == id);
}

void Log(string message, string memberName)
{
    logger.Log(LogLevel.Info, message, memberName);
}

Notes

Non-method names will appear as the C# compiler-generated internal names, that is:

  • .ctor for constructors
  • .cctor for static constructors
  • Finalize for destructors
  • op_operationName for operator overloads
  • op_Implicit for implicit conversion operators
  • op_Explicit for explicit conversion operators

More information