In C#, how do [CallerMemberName] and the other caller-info attributes let OnPropertyChanged or a trace helper work without string literals?
answer
- optional parameters with defaults
- the compiler fills them in
- rename-safe property notifications
- argument source text since C# 10
basics
~10 sCaller-info attributes mark optional parameters that the compiler fills at each call site: [CallerMemberName] with the calling member's name, [CallerFilePath] and [CallerLineNumber] with its location, and [CallerArgumentExpression] with another argument's source text.
solid answer
~40 sThe four attributes in `System.Runtime.CompilerServices` go on **optional** parameters with a default value. When the caller omits the argument, the compiler substitutes a literal: `[CallerMemberName]` the calling method, property or event name, `[CallerFilePath]` the source path at compile time, `[CallerLineNumber]` the line, and `[CallerArgumentExpression(nameof(condition))]` (C# 10) the source text of another argument. So `OnPropertyChanged([CallerMemberName] string? propertyName = null)` called from the `Operation` setter receives `"Operation"`, and a rename updates it. The values are compile-time literals in the caller's IL, not a stack walk, so they cost nothing at run time and survive obfuscation. An explicit argument overrides them, and a parameter without a default is CS4022.
code
csharp · 34 linesusing System.ComponentModel;
using System.Runtime.CompilerServices;
var vm = new OperationViewModel();
vm.PropertyChanged += (_, e) => Console.WriteLine($"changed: {e.PropertyName}");
vm.Operation = "checkout";
Probe.Where();
Probe.Check(vm.Operation.Length > 20);
public sealed class OperationViewModel : INotifyPropertyChanged
{
private string _operation = "";
public event PropertyChangedEventHandler? PropertyChanged;
public string Operation
{
get => _operation;
set { _operation = value; OnPropertyChanged(); } // compiler passes "Operation"
}
private void OnPropertyChanged([CallerMemberName] string? propertyName = null) =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
static class Probe
{
public static void Where([CallerMemberName] string member = "",
[CallerFilePath] string file = "", [CallerLineNumber] int line = 0) =>
Console.WriteLine($"{member} at {Path.GetFileName(file)}:{line}");
public static void Check(bool condition,
[CallerArgumentExpression(nameof(condition))] string? expression = null) =>
Console.WriteLine(condition ? "ok" : $"check failed: {expression}");
}go deeper
Recall the INotifyPropertyChanged pattern: OnPropertyChanged with a [CallerMemberName] optional parameter, called with no argument from each setter.
Explain that the compiler inserts literals at the call site, list the four attributes and their types, and note that explicit arguments override them.
Use caller info for cheap structured logging instead of stack traces, know the build-machine file path and the immediate-caller limit, and when to pass nameof explicitly.
Weigh caller-info diagnostics in shared libraries: they add optional parameters to public signatures, which constrains future overloads and binary compatibility.
## The four caller-info attributes Caller-info attributes ask the **compiler** to pass information about the call site. They live in `System.Runtime.CompilerServices`: | Attribute | Parameter type | Filled with | |---|---|---| | `[CallerMemberName]` | `string` | name of the calling method, property or event | | `[CallerFilePath]` | `string` | full path of the caller's source file at compile time | | `[CallerLineNumber]` | `int` | line number of the call | | `[CallerArgumentExpression("param")]` (C# 10) | `string` | source text of the argument passed for `param` | Each must decorate an **optional** parameter, one with a default value. The attribute does not make the parameter optional; it changes what the compiler passes when the caller leaves the argument out. Without a default, the SDK compiler reports **CS4022**, "The CallerMemberNameAttribute may only be applied to parameters with default values" (the other attributes have equivalent errors). ## How the value gets there At every call that omits the argument, the compiler emits a **literal** into the caller's IL: a string constant or an integer. Consequences: - No stack walk happens at run time, unlike building a `StackTrace`, so the cost is that of passing a constant. - Obfuscation, inlining and release optimizations cannot change the value, because it was fixed at compile time. - The caller can pass its own value, which simply replaces the literal. `Check(ok, "custom text")` uses `"custom text"`. ## CallerMemberName and property notifications The classic use is `INotifyPropertyChanged`. Without the attribute every setter writes `OnPropertyChanged("Operation")`, and a property rename leaves a stale string that breaks data binding silently. With it: ```csharp private void OnPropertyChanged([CallerMemberName] string? propertyName = null) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); public string Operation { get => _operation; set { _operation = value; OnPropertyChanged(); } // passes "Operation" } ``` Inside a property accessor the compiler passes the **property** name, not the accessor's `set_Operation` metadata name. Other members produce: - a constructor: `".ctor"`; a static constructor: `".cctor"`; a finalizer: `"Finalize"`; - a user-defined operator or conversion: its generated name, such as `"op_Addition"`; - top-level statements: `"<Main>$"`, the generated entry point's name (verified on the SDK 10.0.401). To notify about a **different** property, for example a computed `Summary` when `Operation` changes, pass it explicitly with `OnPropertyChanged(nameof(Summary))`; `nameof` keeps that rename-safe too. ## File, line and argument expression `[CallerFilePath]` and `[CallerLineNumber]` together give a log line a location without exceptions or debug symbols: `Where()` called on line 7 prints `<Main>$ at q5.cs:7`. The file path is the path on the build machine, which matters if you ship logs from production. `[CallerArgumentExpression(nameof(condition))]`, added in C# 10, captures the **text** of what the caller wrote for another parameter. `Check(vm.Operation.Length > 20)` receives the string `"vm.Operation.Length > 20"`, so an assertion helper can report what failed without the caller repeating it. The parameter name in the attribute must name another parameter of the same method; a wrong name or a self-reference only produces a warning and leaves the default value. The BCL's argument guard helpers rely on the same attribute; their behaviour is covered with exception handling. ## Walking through the example The snippet wires a view model's `PropertyChanged` event to the console and calls two helpers from top-level statements: - Assigning `vm.Operation = "checkout"` runs the setter, whose bare `OnPropertyChanged()` call receives `"Operation"`, so the handler prints `changed: Operation`. - `Probe.Where()` is called from top-level statements on line 7 of `q5.cs`, so its three caller-info parameters receive `<Main>$`, the full build path of `q5.cs` (trimmed with `Path.GetFileName`) and `7`. - `Probe.Check(vm.Operation.Length > 20)` passes `false` for `condition` and the text `vm.Operation.Length > 20` for `expression`, so the helper prints `check failed: vm.Operation.Length > 20` without the caller writing the text twice. None of these values is looked up when the program runs; open the compiled IL and each call site already contains the string or integer constant. ## Limits worth knowing 1. The value describes the **immediate** caller only; a helper that forwards to another helper must forward the parameter, or the inner one reports the outer helper's name. 2. In contexts where optional arguments cannot be used, the compiler warns that the attribute will have no effect. 3. `[CallerMemberName]` gives a name, not a member: it cannot tell overloads apart. 4. These are compile-time features; a call made through reflection gets no caller info, so it must pass values itself or receive the declared defaults.
- What does [CallerMemberName] receive when the call comes from a constructor or from top-level statements?From an instance constructor it receives `".ctor"`, from a static constructor `".cctor"`, and from top-level statements the generated entry point's name, `"<Main>$"`. Those are metadata names, so a helper that logs the member name should expect them rather than the type name.
- Why prefer caller-info attributes over new StackTrace() to find the calling method?The caller-info values are compile-time literals: no stack walk, no allocation of frames, no dependence on debug symbols, and no distortion from inlining or obfuscation. A `StackTrace` is built at run time, costs far more and can report an unexpected frame after inlining. The trade-off is that caller info only describes the immediate call site.
- Thinks the caller name is found by walking the stack at run time
- Applies [CallerMemberName] to a parameter without a default value
- Expects "set_Operation" rather than "Operation" from a property setter
- Believes an explicitly passed argument is ignored in favour of the caller info
- Thinks [CallerArgumentExpression] passes the argument's evaluated value as text