C# 5.0 Caller Information Attributes: Simplifying Logging and Diagnostics

Zero-reflection diagnostic logging. We explore compiler-injected parameters and lightweight trace logs in C# 5.0.

VP
SHIVAM ITCS
·25 December 2013·10 min read

The Cost of Runtime Reflection

To write detailed trace logs containing file paths, class names, and line numbers, developers traditionally relied on System.Diagnostics stack traces.

  • The Issue: Retrieving stack trace metadata at runtime requires reflection, which is slow and degrades system performance.
  • The Solution: C# 5.0 Caller Information Attributes, allowing the compiler to inject metadata directly into parameters.

Performance Rule: Use Caller Information attributes to capture source file and line numbers, avoiding runtime reflection overhead.

The Caller Attributes

C# 5.0 introduces three caller attributes in the System.Runtime.CompilerServices namespace:

  • CallerFilePathAttribute: Injects the full source path of the caller file.
  • CallerLineNumberAttribute: Injects the line number where the call is made.
  • CallerMemberNameAttribute: Injects the method or property name of the caller.

Implementing a Diagnostic Logger

csharpcode
// High-performance logger class in C# 5.0
public static class DiagnosticsLogger {
    public static void LogTrace(string message,
        [CallerMemberName] string memberName = "",
        [CallerFilePath] string filePath = "",
        [CallerLineNumber] int lineNumber = 0) {
        
        string logMsg = string.Format("[TRACE] {0} -> Method: {1}, File: {2}, Line: {3}",
            message, memberName, Path.GetFileName(filePath), lineNumber);
            
        Console.WriteLine(logMsg);
    }
}

Because the compiler substitutes these parameters with literals at compile-time, trace logging runs with zero runtime reflection overhead.

VP
Vijay Paliwal
Founder, SHIVAM ITCS · 18+ years enterprise & AI engineering
MCA · Ex-HiveGPT USA · Ex-Social27 Seattle
C# 5.0 Caller Information Attributes: Simplifying Logging and Diagnostics | SHIVAM ITCS Blog | SHIVAM ITCS