ADocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
ref readonly parameter is a method parameter modifier introduced in C# 12 that passes an argument by reference while strictly enforcing immutability within the called method. It provides the memory-address passing semantics of the ref keyword combined with the non-mutability guarantees of the in keyword, while prompting the caller to explicitly acknowledge the pass-by-reference behavior at the call site to avoid compiler warnings.
Syntax and Call Site Mechanics
When declaring a method, theref readonly modifiers precede the parameter type. At the call site, the caller is expected to apply either the ref or in keyword to the argument. Omitting the keyword is permitted by the compiler but generates a warning.
Technical Characteristics
1. Immutability Enforcement The compiler treats the parameter as an immutable alias to the original variable. Any attempt to reassign the parameter, modify its fields (if it is a value type), or pass it as a writableref or out parameter to another method results in a compilation error.
2. L-Value Requirement and Defensive Copies
ref readonly expects an l-value (a variable with a defined memory location). If an r-value (such as a literal, property, or method return value) is passed, the compiler must create a hidden temporary variable to generate a memory address. Unlike the in modifier, which does this silently, ref readonly issues a compiler warning to alert the developer of the hidden allocation.
ref readonly and in is call-site visibility. The in modifier allows the caller to omit the keyword entirely without penalty, obscuring the fact that a reference is being passed. ref readonly expects the caller to use ref or in, issuing a warning (CS9192) if omitted, thereby making the reference semantics visible in the calling code without breaking compilation.
4. Intermediate Language (IL) Representation
At the IL level, ref readonly, in, and ref all compile to managed pointers (&). To differentiate ref readonly and in from standard ref, the C# compiler applies the [IsReadOnly] attribute to the parameter metadata. To specifically distinguish ref readonly from in, the compiler applies the [RequiresLocation] attribute to ref readonly parameters. This attribute signals in the metadata that the parameter strictly expects an l-value, differentiating its call-site requirements from those of an in parameter.
5. Overload Resolution
Methods cannot be overloaded if they differ only by ref, in, out, or ref readonly. The compiler considers them identical for signature matching.
Master C# with Deep Grasping Methodology!Learn More





