Skip to content

Ref return C# 7.0performance

Return references to variables instead of copies of values.

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 directly
csharp
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 indexing

Notes ​

  • The method needs ref on the return type and on every return statement
  • To keep the reference the caller must also use ref twice, 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;
  • 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 ref to a local variable)
  • Properties and indexers can also return by ref
  • Async methods cannot return by ref

More information ​

Powered by Intracia