By Reference
The ref Modifier
The ref keyword passes a variable by reference, allowing the callee to modify the caller’s value:
void Increment(ref int x){ x = x + 1;}
int val = 5;Increment(val); // val is now 6Swap Example
void Swap(ref int a, ref int b){ int temp = a; a = b; b = temp;}
int x = 10;int y = 20;Swap(x, y); // x=20, y=10Works with Any Type
ref works with value types, GC references, and pointer types:
void UpdateRef(ref Node? n){ n = new Node(42);}
void ModifyPointer(ref int* p) unsafe{ p = new* int();}Range-Based For Loops
Use ref in for-each loops to modify elements in place:
int[] arr = new int[3];arr[0] = 1;arr[1] = 2;arr[2] = 3;
for (ref int x : arr){ x = x * 10;}// arr is now [10, 20, 30]The in Modifier
in is syntactic sugar for immut ref — it passes by reference but prevents modification. This is useful for passing large types efficiently without copying:
int Sum(in Point p){ return p.x + p.y; // p.x = 10; // ERROR: cannot modify in parameter}
Point pt;pt.x = 10;pt.y = 20;Sum(pt); // 30| Modifier | Meaning |
|---|---|
ref | Mutable by-reference |
in | Immutable by-reference (immut ref) |
in is only valid as a parameter modifier (not for local variables or return types).
How It Works
- The caller passes the variable’s address (not its value)
- The callee reads and writes through the pointer transparently
- For GC types, write barriers are emitted when storing through a
ref
Rules
refparameters receive the address of the caller’s variable- The caller must pass an lvalue (a variable, field, or array element)
refcannot be used with callable binding (bound methods do not supportrefreceivers)