What are ref returns and ref locals in C#?
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]; }thenref int slot = ref Find(arr, x); slot = 99;updatesarr[i].- Can't ref-return a local variable (it would dangle) or a property with a normal setter.
inparameters are read-only ref — pass a big struct without copying it, without letting the method change it.- Used heavily inside
Span<T>,Dictionary'srefAPIs (CollectionsMarshal.GetValueRefOrNullRef), and high-perf libraries.