The ref keyword indicates a value that is passed by reference. It is used in four different contexts:
- In a method signature and in a method call, to pass an argument to a method by reference.
- In a method signature, to return a value to the caller by reference.
- In a member body, to indicate that a reference return value is stored locally as a reference that the caller intends to modify or, in general, a local variable accesses another value by reference.
- In a struct declaration to declare a ref struct or a readonly ref struct.
Passing an argument by reference
When used in a method’s parameter list, the ref keyword indicates that an argument is passed by reference, not by value. The ref keyword makes the formal parameter an alias for the argument, which must be a variable.
1 | void Method(ref int refArgument) |
Reference return values
1 | public static ref int Find(int[,] matrix, Func<int, bool> predicate) |
Ref locals
A ref local variable is used to refer to values returned using return ref
.