Understanding readonly ref in C#
Learn how readonly ref in C# lets you return and pass large structs by reference without mutation, reducing copies and improving performance.

When a method returns a large struct, the default behavior is to copy the entire value. For types like Vector3 or BigInteger, that copy can dominate the cost of the call. A group of related C# features—ref readonly returns, in parameters, and readonly ref struct types—lets you pass or return a struct by reference while preventing mutation through that reference. This combines the efficiency of a reference with the safety of a read-only view.
What readonly ref Means in C#
The term readonly ref covers two common C# modifiers: ref readonly for return values and in for parameters. Both express a read-only reference: the underlying value is passed by reference, and the receiving code cannot assign to it through that reference.
public ref readonly Vector3 GetPosition()
{
return ref _position;
}
public double Distance(in Vector3 a, in Vector3 b)
{
double dx = a.X - b.X;
double dy = a.Y - b.Y;
return Math.Sqrt(dx * dx + dy * dy);
}In the first method, GetPosition returns a reference to the internal _position field. The caller can read position.X through a ref readonly local, but cannot assign a new value through that same reference. The second method takes in parameters, so Distance can read a and b but cannot mutate them. This is the foundation for avoiding copies of large structs.
Using ref readonly Returns to Avoid Copies
Returning a large struct by value forces a copy at the call site. If the struct is part of a collection or a long-lived object, that copy happens every time the property is accessed. A ref readonly return eliminates that copy because the caller receives a reference to the original data.
public class Mesh
{
private BoundingBox _bounds;
public ref readonly BoundingBox Bounds => ref _bounds;
}Here, Bounds returns a reference to the internal _bounds field. The caller can read mesh.Bounds.Min and mesh.Bounds.Max without copying the entire BoundingBox. The compiler enforces that the caller cannot assign through the returned reference. This pattern is useful for frequently accessed properties that return large structs.
One important detail is that the returned reference must refer to storage that outlives the method call. The compiler will reject a ref readonly return that refers to a local variable, because the local would be destroyed when the method exits. Fields and array elements are common safe targets.
Passing Structs by in for Read-Only Parameters
The in parameter modifier is the parameter-side counterpart of ref readonly. It tells readers of the signature that the argument is passed by reference but treated as read-only inside the method. This is particularly beneficial when the method only reads the struct, because it can avoid copying the entire argument.
public static float ComputeArea(in Rectangle rect)
{
return rect.Width * rect.Height;
}Callers can pass a Rectangle directly: ComputeArea(myRect). The compiler may pass a reference to myRect instead of copying it. However, there are cases where the compiler must make a defensive copy. If the method passes the in parameter to another method that expects a by-value parameter, or if it stores the parameter in a field, the compiler may create a local copy to preserve the read-only guarantee. This is subtle but important: in does not guarantee zero copies in all scenarios.
readonly ref struct for Stack-Only Types
A readonly ref struct is a ref struct that is also a readonly struct. The ref struct part restricts the type to the stack, so it cannot be boxed or stored on the managed heap. The readonly struct part requires instance fields to be readonly and prevents members from mutating the struct. This combination is used by types such as Span<T> and ReadOnlySpan<T>.
public readonly ref struct SensorReading
{
public readonly double Temperature;
public readonly double Humidity;
public SensorReading(double temperature, double humidity)
{
Temperature = temperature;
Humidity = humidity;
}
}This type can only be used on the stack, which makes it safe to pass by reference without worrying about heap allocation. It is useful in high-performance code that processes large amounts of data in a tight loop, such as parsing network packets or reading binary files.
Performance and Allocation Considerations
The primary benefit of readonly ref is reducing memory traffic. Copying a large struct involves reading and writing many bytes. By passing a reference, the CPU handles a pointer instead. This can reduce the number of memory operations in performance-sensitive paths, but it is not automatic: defensive copies, indirection, and call overhead can still matter.
in parameters and ref readonly returns are not a guarantee that no copies will occur. The compiler may copy when it must preserve the read-only model, such as when an in parameter is passed to a by-value parameter or stored in a field. If performance is critical, measure the actual behavior rather than assuming that a reference is always faster.
A ref readonly return follows the lifetime of the storage it references. In safe C# code, the compiler enforces basic rules that prevent dangling references. If you return a reference to an array element, the reference stays tied to that array element; resizing a collection that replaces its internal array does not automatically invalidate the reference. Keep returned references short-lived and avoid exposing internal storage when the owning object can replace it.
Common Pitfalls and How to Avoid Them
Trying to return a ref readonly from a property that computes a value on the fly is a common mistake. A property that returns new Vector3(x, y, z) cannot be a ref readonly because the value is a temporary. The compiler will reject this with an error. The solution is to store the value in a field and return a reference to that field.
in parameters do not guarantee a copy-free call. Passing an in parameter to a by-value method, storing it in a field, or passing an expression rather than a variable can all produce a copy. This is not usually a correctness problem, but it matters in hot paths. Benchmark the code if avoiding copies is the goal. If you need a guaranteed mutable reference, use ref; if you need a read-only reference, in is the API-level contract even though the implementation may copy.
A readonly ref struct cannot be used in places where the runtime would need to store it on the heap. It cannot be a field in a normal class, cannot be boxed, and cannot be used in async or iterator methods where the compiler's state machine would capture it. If you need to store the data, copy it into a regular struct or use a different design.
When to Use readonly ref vs. Other Approaches
Use ref readonly returns when you have a large struct that is frequently accessed and you want to avoid copying it. This is common in game engines, scientific computing, and data processing pipelines. Use in parameters when a method only reads a large struct and you want to avoid copying the argument. This works well for math functions, comparison methods, and serialization logic.
For small structs, usually 16 bytes or fewer, passing by value is often simpler and can be faster than a reference. Base the decision on the struct size, the frequency of the operation, and measurements rather than on a fixed rule.
A readonly ref approach can also be useful for returning an item from an array or a custom collection that provides a ref-returning indexer. A standard List<T> indexer returns by value, so it does not support this pattern directly.
If callers need to modify the value, use ref rather than ref readonly. The readonly modifier is a contract preventing mutation; if the caller must update the value, the method should return a mutable reference.
Finally, consider lifetime. A ref readonly return is tied to the storage it references. If that storage is a field in a class, the reference is valid as long as the class instance is reachable. If the storage is an array element, the reference remains tied to that array, even if a later resize replaces the collection's current array. Keep returned references short-lived so callers do not accidentally observe stale data. The compiler enforces the basic safe-lifetime rules, but careful API design is still required.
Try matching browser tools
All toolsSmall utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related C# guides
All C# guidesC# Dispose vs Destructor: Key Differences Explained
c# dispose vs destructor: Understand the difference between Dispose and destructors in C#, when each runs, and how to manage unmanaged resources correctly.
C# Variable Declaration: Syntax and Practical Usage
Learn how to declare variables in C# with explicit types, var, and nullable annotations, and understand how defaults, scope, and readability affect your choices.
C# Primary Constructors for Classes: Syntax and Usage
Learn how to use C# primary constructors for classes: syntax, initialization, dependency injection, and limitations with practical examples.
C# IComparer: Custom Sorting with IComparer<T>
Learn how to implement IComparer<T> in C# to define custom sort order for arrays and lists, handle nulls, and avoid common performance pitfalls.
More in C#
All C# guidesThe guides filed next to this one in C#, in library order.