Source-level info (Caller attributes)
Use CallerMemberName, CallerFilePath, and CallerLineNumber to capture call-site info for logs, guards, and property notifications.
Why caller info
Aim: Capture call-site info automatically.
- CallerMemberName — who called
- CallerFilePath — which file
- CallerLineNumber — which line
- Great for logs, guards, and notifications
Member name for logs
CallerMemberName auto-fills the caller's method/property name when the argument is omitted.
using System;
using System.Runtime.CompilerServices;
public static class Log
{
// Caller fills "member" automatically if not provided
public static void Info(string msg, [CallerMemberName] string member = null)
{
Console.WriteLine("[" + (member ?? "?") + "] " + msg);
}
}
public class Program
{
static void DoWork() { Log.Info("started"); }
public static void Main(string[] args)
{
Log.Info("app boot");
DoWork(); // prints caller method name
}
}
All lessons in this course
- Type, MethodInfo, activation, custom attributes
- Source-level info (Caller attributes)
- Light metaprogramming scenarios