Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

C# Struct Copy Behavior: Value Type Semantics Explained

Understand how C# structs are copied by value, why it matters for performance and correctness, and how to control copy behavior with ref, readonly, and in parameters.

~5 min readC#
#C# structs#value types#copy semantics#performance
Diagram illustrating a struct being copied by value into a new memory location in C#.

In C#, structs are value types. Assigning a struct to another variable, passing it to a method, or returning it from a method copies the struct's fields. That copy behavior matters for both performance and correctness, especially when a struct is large or used in collections. This article explains when copies happen, how the copy is made, and how to control copying with ref, readonly, and in.

What Happens When You Assign a Struct to Another Variable

Consider a simple struct definition:

csharp
public struct Point { public int X; public int Y; }

When you assign one Point variable to another, the runtime copies all field values from the source to the destination. The two variables now hold independent copies, so modifying one does not affect the other.

csharp
Point a = new Point { X = 1, Y = 2 }; Point b = a; b.X = 10; Console.WriteLine(a.X); // Output: 1 Console.WriteLine(b.X); // Output: 10

This differs from classes, where assignment copies only the reference and both variables refer to the same object. For structs, the copy is shallow: reference-type fields are copied as references, but the objects they point to are not duplicated.

Passing Structs to Methods: By Value vs. By Ref

Passing a struct to a method without a modifier passes a copy. Changes made to the parameter do not affect the caller's variable.

csharp
public void ModifyPoint(Point p) { p.X = 100; } Point original = new Point { X = 1, Y = 2 }; ModifyPoint(original); Console.WriteLine(original.X); // Still 1

To let the method modify the original struct, pass it by reference:

csharp
public void ModifyPoint(ref Point p) { p.X = 100; } ModifyPoint(ref original); Console.WriteLine(original.X); // Now 100

out is similar for output-only parameters. in passes a read-only reference and is covered later in this article. The choice between passing by value and by reference affects both correctness and performance.

Struct Copy Semantics with Arrays and Collections

An array stores struct values directly. An element access such as points[0] is a variable, so you can modify that element in place:

csharp
points[0].X = 100; // Modifies the array element directly

However, copying an element into a local variable creates a separate copy:

csharp
Point first = points[0]; first.X = 100; Console.WriteLine(points[0].X); // Still 1

List<T> behaves differently: its indexer returns the value, not a variable. The same direct element assignment fails because the indexer result is a copy:

csharp
List<Point> pointList = new List<Point>(); pointList.Add(new Point()); pointList[0].X = 100; // Error: cannot modify the return value because it is not a variable

To modify a struct stored in a List<T>, copy it out, modify the copy, and assign it back:

csharp
Point p = pointList[0]; p.X = 100; pointList[0] = p;

These copy-on-access rules are a common source of confusion for developers coming from reference types.

Performance Implications of Struct Copying

Copying a struct copies all of its fields. For small structs like Point, the cost is low. For larger structs with many value-type fields, or in hot paths where copies are repeated, the cost can become significant.

csharp
public struct LargeBuffer { public byte[] Data; // Reference field: copying copies the reference, not the array public int Size; // ... additional value-type fields determine most of the copy size }

Reference-type fields do not make a struct itself proportionally larger to copy; copying them copies only the reference. To reduce copying, you can use ref parameters, ref returns, or design structs to be small and immutable.

Readonly Structs and In Parameters

A readonly struct is an immutable struct type. The compiler enforces that its instance fields are readonly and that instance members do not write to the struct's state. This prevents accidental mutation and makes in parameters more efficient.

When you pass a struct by in, the compiler uses a read-only reference instead of making a copy at the call site for variable arguments. This can avoid copying large structs while still preventing the callee from modifying the caller's value.

csharp
public readonly struct ImmutablePoint { public int X { get; } public int Y { get; } public ImmutablePoint(int x, int y) { X = x; Y = y; } } public double DistanceFromOrigin(in ImmutablePoint p) { return Math.Sqrt(p.X * p.X + p.Y * p.Y); }

The benefit of in is strongest for readonly structs. For a non-readonly struct, the compiler may create a defensive copy whenever an instance member is accessed through the in parameter, because it cannot guarantee that the member does not modify the struct. That defensive copy can negate the performance benefit.

Using Ref Returns to Avoid Copies

When you need to return a struct from a method, or expose an element from a collection without copying it, you can use a ref return. This is especially useful with large structs stored in arrays.

csharp
private Point[] _points; public ref Point GetPoint(int index) { return ref _points[index]; } // Usage ref Point p = ref GetPoint(0); p.X = 42; // Modifies the array element directly

This technique avoids copying the struct on return and lets the caller modify the original data. It should be used carefully because it exposes internal storage and can create aliasing issues.

Common Pitfalls and Misconceptions

One common mistake is assuming that assigning a struct to a new variable creates a reference. It does not: the new variable is an independent copy, so modifications do not propagate back.

Another pitfall is trying to modify a struct returned from a property or indexer. For arrays, points[0].X = 100 works because an array element is a variable. For types whose indexer returns a copy, such as List<T>, the same code is a compile-time error. Copy the struct, modify the copy, and assign it back.

Choosing Between Struct and Class Based on Copy Behavior

Struct copy semantics influence the choice between struct and class. Structs are appropriate when the value is small, logically immutable, and represents a single value, such as a coordinate, a color, or a range. Classes are better when identity matters, when the data is large, or when reference semantics are needed.

CriterionStructClass
Copy behaviorCopied by valueReference copied
Memory allocationTypically stored inline or on the stackHeap allocated
Performance for large dataCopy cost can be highReference copy is cheap
IdentityNo identity; two copies are equalEach instance has identity
Typical useSmall, immutable valuesLarger, mutable objects

If you need to avoid copying large structs, ref and in can help, but they add complexity. In many cases, a class is simpler and more maintainable for large data structures.

When Copy Behavior Causes Unexpected Aliasing

Even though structs are copied by value, they can contain reference-type fields. Copying such a struct copies those references, so the two structs can share the same mutable object.

csharp
public struct Container { public List<int> Items; } Container c1 = new Container { Items = new List<int> { 1, 2, 3 } }; Container c2 = c1; c2.Items.Add(4); Console.WriteLine(c1.Items.Count); // 4, because both share the same List

This is a subtle side effect of shallow struct copying. If fully independent copies are required, implement deep copying or design the struct to contain only value types.

Defensive Copies and the in Modifier

When you pass a non-readonly struct by in, the compiler may create a defensive copy before calling an instance member if it cannot prove that the member will not modify the struct. The copy guarantees that the original value is unchanged, but it can also eliminate the performance benefit of avoiding the copy.

csharp
public struct MutablePoint { public int X; public int Y; } public void Check(in MutablePoint p) { // Accessing p may require a defensive copy because MutablePoint is not readonly. }

Marking the struct readonly is the clearest way to avoid defensive copies and make in parameters predictable.

Try matching browser tools

All tools

Small utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.

All C# guides

More in C#

All C# guides

The guides filed next to this one in C#, in library order.