Skip to main content
A ref local variable is a local variable that acts as a direct alias to another variable’s memory location rather than storing a discrete copy of its value. Any read or write operation performed on the ref local is executed directly against the underlying memory address of the aliased variable.

Syntax and Initialization

To declare a ref local, the ref keyword must precede both the type declaration and the initialization expression.

Reference Reassignment (C# 7.3+)

By default, assigning a value to a ref local overwrites the value at the referenced memory location. However, using the ref keyword during assignment allows the ref local to be repointed to an entirely different memory location.

ref readonly Locals

You can enforce immutability on the aliased memory location by declaring the local as ref readonly. This permits reading from the memory address while preventing any modifications through the alias.

Technical Constraints and Rules

  1. Mandatory Initialization: A ref local must be initialized at the time of declaration. It cannot be declared uninitialized and assigned later.
// Compiler Error: A ref local must be initialized // ref int invalidRef;