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 in System.Runtime.CompilerServices that you apply to optional parameters. When the caller omits the argument the compiler fills it in:

  • CallerMemberName with the name of the method or property that made the call
  • CallerFilePath with the full path of the source file containing the call
  • CallerLineNumber with the line number of the call within that source file

Code ​

csharp
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);
}
csharp
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 ​

  • Calls from a property accessor report the property name, which makes CallerMemberName a popular way to raise INotifyPropertyChanged events without repeating the property name
  • Other non-method callers appear as their compiler-generated internal names:
    • .ctor for constructors
    • .cctor for static constructors
    • Finalize for finalizers
    • op_Addition style names for operator overloads
    • op_Implicit for implicit conversion operators
    • op_Explicit for explicit conversion operators
  • CallerArgumentExpression C# 10.0 adds a similar attribute that captures the source text of an argument

More information ​

Powered by Intracia