C# 7.0 introduces the ability to return references to variables rather than their values. This allows methods to return a reference to a location in memory that can be read from or written to directly, avoiding the cost of copying large value types.
This feature is particularly useful when working with large structs or arrays where copying data would be expensive. Combined with ref locals C# 7.0, you can work with references throughout your code for maximum performance.
WARNING
Using ref can lead to unexpected side effects and code that is hard to follow and debug. It should be used sparingly when measured performance requirements and gains require that trade-off.
Code
csharp
ref int FindFirst(int[] array, int value) {
for (int i = 0; i < array.Length; i++) {
if (array[i] == value)
return ref array[i];
}
throw new InvalidOperationException();
}
ref int match = ref FindFirst(numbers, 42);
match = 100; // Modifies the array directlycsharp
int FindFirstIndex(int[] array, int value) {
for (int i = 0; i < array.Length; i++) {
if (array[i] == value)
return i;
}
throw new InvalidOperationException();
}
int index = FindFirstIndex(numbers, 42);
numbers[index] = 100; // Requires separate indexingNotes
- The method needs
refon the return type and on everyreturnstatement - To keep the reference the caller must also use
reftwice,ref int match = ref FindFirst(...)- Without it,
int match = FindFirst(...)silently takes a copy and changes do not reach the array - The result can also be used directly without a local, e.g.
FindFirst(numbers, 42) = 100;
- Without it,
- ref readonly C# 7.2 returns prevent modification while still avoiding copies
- The returned reference must have a lifetime that extends beyond the method (e.g., you cannot return
refto a local variable) - Properties and indexers can also return by
ref - Async methods cannot return by
ref