What are ref returns and ref locals in C#?

C# Methods & Parameters Advanced 3–5 Yrs5+ Yrs Conceptual 1 min read

Quick Answer

A ref return returns a reference to a variable (e.g. an array slot) rather than a copy, so the caller can read and write the original through a ref local. It's a performance feature for avoiding copies of large structs and for in-place mutation of collection elements — rare in everyday code.

A ref return hands back a reference to an actual storage location — say an array element — instead of a copy of its value. Combined with a ref local, the caller can then read and write that original location directly. It's a niche performance tool: avoiding the copy of a large struct, or updating a collection element in place without an indexer round trip. You'll see it inside Span and some of the newer high-performance dictionary APIs, but it's not something I'd use in normal business code.

  • ref int Find(int[] arr, ...) { return ref arr[i]; } then ref int slot = ref Find(arr, x); slot = 99; updates arr[i].
  • Can't ref-return a local variable (it would dangle) or a property with a normal setter.
  • in parameters are read-only ref — pass a big struct without copying it, without letting the method change it.
  • Used heavily inside Span<T>, Dictionary's ref APIs (CollectionsMarshal.GetValueRefOrNullRef), and high-perf libraries.