ZetCode

C# Copy by Value vs Copy by Reference

last modified November 15, 2026

This article explains what happens when C# variables are assigned to other variables and passed to methods. Whether the data is copied or shared depends on whether the type is a value type or a reference type.

Value types and reference types

A variable of a value type contains the data directly. Value types are the simple types like int, double, bool, and char, plus enums, structs, and tuples.

A variable of a reference type contains a reference to an object; the object itself lives elsewhere, on the managed heap. Classes, records declared with record or record class, arrays, strings, delegates, and object are reference types.

Assignment in C# always copies the content of the variable. For a value type, this content is the data, so the result is an independent copy. For a reference type, the content is the reference, so after the assignment two variables refer to the same object. This is often called copy by reference, although strictly speaking the reference is copied by value.

Characteristic Value types Reference types
Variable contains The data A reference to an object
Assignment copies The data (independent copy) The reference (shared object)
Can be null No (only Nullable<T>) Yes
Examples int, double, struct, enum class, arrays, string, List<T>

It is often said that value types live on the stack and reference types on the heap. This is only partly true. A local int variable is usually on the stack, but an int field of a class or an element of an int[] array lives on the heap, inside the object. What matters for program behavior is the copy semantics, not the location.

Copy by value

Assigning a value type creates an independent copy. This holds for built-in types as well as for user-defined structs.

Program.cs
int a = 10;
int b = a;

b = 20;
Console.WriteLine($"a = {a}, b = {b}");

Point p1 = new(1, 2);
Point p2 = p1;

p2.X = 10;
Console.WriteLine($"p1 = {p1}, p2 = {p2}");

struct Point(int x, int y)
{
    public int X = x;
    public int Y = y;

    public override readonly string ToString() => $"({X}, {Y})";
}

We copy an integer and a struct and modify the copies.

int b = a;

b = 20;

b receives a copy of the value 10. Changing b does not affect a.

Point p2 = p1;

p2.X = 10;

Assigning a struct copies all of its fields. p2 is a separate point; changing its X field leaves p1 untouched.

$ dotnet run
a = 10, b = 20
p1 = (1, 2), p2 = (10, 2)

Copy by reference

Assigning a class instance copies the reference. Both variables then refer to the same object.

Program.cs
Person p1 = new("Alice");
Person p2 = p1;

p2.Name = "Bob";
Console.WriteLine($"p1 = {p1.Name}, p2 = {p2.Name}");
Console.WriteLine(ReferenceEquals(p1, p2));

p2 = new Person("Carol");
Console.WriteLine($"p1 = {p1.Name}, p2 = {p2.Name}");
Console.WriteLine(ReferenceEquals(p1, p2));

class Person(string name)
{
    public string Name { get; set; } = name;
}

We assign a Person object to a second variable.

p2.Name = "Bob";

The change made through p2 is visible through p1, because there is only one object. ReferenceEquals confirms that both variables refer to it.

p2 = new Person("Carol");

Assigning a new object to p2 changes only the variable p2. The first object and the p1 variable are not affected. Modifying an object and assigning a new object to a variable are two different operations.

$ dotnet run
p1 = Bob, p2 = Bob
True
p1 = Bob, p2 = Carol
False

Copying arrays

Arrays are reference types, even when their elements are value types.

Program.cs
int[] arr1 = [1, 2, 3];
int[] arr2 = arr1;

arr2[0] = 99;
Console.WriteLine($"arr1 = [{string.Join(", ", arr1)}]");

int[] arr3 = (int[])arr1.Clone();
int[] arr4 = [.. arr1];
int[] arr5 = new int[arr1.Length];
Array.Copy(arr1, arr5, arr1.Length);

arr3[0] = 1;
arr4[1] = 20;
arr5[2] = 30;

Console.WriteLine($"arr1 = [{string.Join(", ", arr1)}]");
Console.WriteLine($"arr3 = [{string.Join(", ", arr3)}]");
Console.WriteLine($"arr4 = [{string.Join(", ", arr4)}]");
Console.WriteLine($"arr5 = [{string.Join(", ", arr5)}]");

We assign an array and then create real copies in three ways.

int[] arr2 = arr1;

arr2[0] = 99;

arr2 refers to the same array, so the change is visible through arr1.

int[] arr3 = (int[])arr1.Clone();
int[] arr4 = [.. arr1];
int[] arr5 = new int[arr1.Length];
Array.Copy(arr1, arr5, arr1.Length);

The Clone method, a collection expression with the spread operator, and Array.Copy create new arrays with the same elements. Changes to the copies do not affect arr1.

$ dotnet run
arr1 = [99, 2, 3]
arr1 = [99, 2, 3]
arr3 = [1, 2, 3]
arr4 = [99, 20, 3]
arr5 = [99, 2, 30]

Shallow and deep copies

The copies from the previous example are shallow: they copy the elements themselves. When the elements are references, the copy contains the same references and shares the objects with the original.

Program.cs
Person[] people = [new("Alice"), new("Bob")];

Person[] shallow = (Person[])people.Clone();
shallow[0].Name = "Alicia";
shallow[1] = new Person("Carol");

Console.WriteLine(string.Join(", ", people.Select(p => p.Name)));
Console.WriteLine(string.Join(", ", shallow.Select(p => p.Name)));

Person[] deep = people.Select(p => new Person(p.Name)).ToArray();
deep[0].Name = "Ann";

Console.WriteLine(string.Join(", ", people.Select(p => p.Name)));
Console.WriteLine(string.Join(", ", deep.Select(p => p.Name)));

class Person(string name)
{
    public string Name { get; set; } = name;
}

We clone an array of Person objects.

Person[] shallow = (Person[])people.Clone();
shallow[0].Name = "Alicia";
shallow[1] = new Person("Carol");

shallow is a new array, but its elements refer to the original objects. Renaming the first person changes the object shared by both arrays. Replacing the second element changes only the new array.

Person[] deep = people.Select(p => new Person(p.Name)).ToArray();

A deep copy creates new objects as well. Here we create a new Person for each element, so the copy is fully independent. The shallow & deep copy article covers this topic in more detail.

$ dotnet run
Alicia, Bob
Alicia, Carol
Alicia, Bob
Ann, Bob

Strings

Strings are reference types, but they are immutable: no operation changes an existing string object. Methods and operators that seem to modify a string return a new one.

Program.cs
string s1 = "hello";
string s2 = s1;

Console.WriteLine(ReferenceEquals(s1, s2));

s2 += " there";
Console.WriteLine($"s1 = {s1}, s2 = {s2}");
Console.WriteLine(ReferenceEquals(s1, s2));

string s3 = s1.ToUpper();
Console.WriteLine($"s1 = {s1}, s3 = {s3}");

We share a string between two variables and "modify" it.

string s2 = s1;

Console.WriteLine(ReferenceEquals(s1, s2));

After the assignment, both variables refer to the same string object.

s2 += " there";

The += operator creates a new string and assigns it to s2. s1 still refers to the original "hello". Since nobody can change a string, sharing it is always safe; strings behave like values even though they are references.

$ dotnet run
True
s1 = hello, s2 = hello there
False
s1 = hello, s3 = HELLO

Structs with reference fields

Copying a struct copies its fields. If a field holds a reference, only the reference is copied.

Program.cs
Holder h1 = new(5, ["a", "b"]);
Holder h2 = h1;

h2.Count = 10;
h2.Items.Add("c");

Console.WriteLine($"h1: {h1.Count}, [{string.Join(", ", h1.Items)}]");
Console.WriteLine($"h2: {h2.Count}, [{string.Join(", ", h2.Items)}]");

struct Holder(int count, List<string> items)
{
    public int Count = count;
    public List<string> Items = items;
}

The Holder struct has an integer field and a list field.

h2.Count = 10;
h2.Items.Add("c");

The copy has its own Count, but both structs refer to the same list. The item added through h2 appears in h1 too. A struct is therefore an independent copy only if all its fields are value types or immutable objects.

$ dotnet run
h1: 5, [a, b, c]
h2: 10, [a, b, c]

Records and the with expression

A record class is a reference type. The with expression creates a new record with some properties changed. The copy is shallow.

Program.cs
var u1 = new User("John", ["admin"]);
var u2 = u1 with { Name = "Jane" };

u2.Roles.Add("editor");

Console.WriteLine($"{u1.Name}, {u2.Name}");
Console.WriteLine(string.Join(", ", u1.Roles));
Console.WriteLine(ReferenceEquals(u1.Roles, u2.Roles));

var u3 = u1 with { Roles = [.. u1.Roles] };
u3.Roles.Add("viewer");

Console.WriteLine(string.Join(", ", u1.Roles));
Console.WriteLine(string.Join(", ", u3.Roles));

record User(string Name, List<string> Roles);

We copy a user record with a list of roles.

var u2 = u1 with { Name = "Jane" };

u2.Roles.Add("editor");

u2 is a new object with a different name, but its Roles property refers to the same list as u1.Roles. The added role appears in both users.

var u3 = u1 with { Roles = [.. u1.Roles] };

To make the copy independent, we create a new list in the with expression.

$ dotnet run
John, Jane
admin, editor
True
admin, editor
admin, editor, viewer

Passing parameters

By default, C# passes arguments by value: the parameter receives a copy of the content of the argument variable. For a reference type, the copy is a reference to the same object.

Program.cs
int number = 10;
ModifyValue(number);
Console.WriteLine($"number = {number}");

int[] numbers = [1, 2, 3];
ModifyElement(numbers);
Console.WriteLine($"numbers = [{string.Join(", ", numbers)}]");

Replace(numbers);
Console.WriteLine($"numbers = [{string.Join(", ", numbers)}]");

void ModifyValue(int x)
{
    x = 20;
}

void ModifyElement(int[] arr)
{
    arr[0] = 100;
}

void Replace(int[] arr)
{
    arr = [7, 8, 9];
    arr[0] = 0;
}

We pass an integer and an array to methods.

void ModifyValue(int x)
{
    x = 20;
}

x is a copy of number; the change is lost when the method returns.

void ModifyElement(int[] arr)
{
    arr[0] = 100;
}

arr refers to the caller's array, so modifying an element is visible outside the method.

void Replace(int[] arr)
{
    arr = [7, 8, 9];
    arr[0] = 0;
}

Assigning a new array to the parameter changes only the local copy of the reference. From that point on, arr refers to a different array, and the caller's array stays [100, 2, 3].

$ dotnet run
number = 10
numbers = [100, 2, 3]
numbers = [100, 2, 3]

ref and out parameters

The ref and out modifiers pass the variable itself instead of a copy. The method can then assign a new value to the caller's variable.

Program.cs
int y = 5;
SetToTen(ref y);
Console.WriteLine($"y = {y}");

int[] numbers = [1, 2, 3];
Replace(ref numbers);
Console.WriteLine($"numbers = [{string.Join(", ", numbers)}]");

if (TryDivide(10, 4, out int q, out int r))
{
    Console.WriteLine($"q = {q}, r = {r}");
}

Console.WriteLine(TryDivide(1, 0, out _, out _));

void SetToTen(ref int n)
{
    n = 10;
}

void Replace(ref int[] arr)
{
    arr = [7, 8, 9];
}

bool TryDivide(int a, int b, out int quotient, out int remainder)
{
    if (b == 0)
    {
        quotient = remainder = 0;
        return false;
    }

    quotient = a / b;
    remainder = a % b;
    return true;
}

We use ref with a value type and a reference type, and out to return two values.

void SetToTen(ref int n)
{
    n = 10;
}

n is an alias for y, so the assignment changes the caller's variable. The ref keyword is required at both the declaration and the call site.

void Replace(ref int[] arr)
{
    arr = [7, 8, 9];
}

With ref, assigning a new array to the parameter does replace the caller's array, unlike in the previous example.

bool TryDivide(int a, int b, out int quotient, out int remainder)

An out argument does not have to be initialized before the call, but the method must assign it on every path. The Try pattern returns success as a bool and the results through out parameters. The ref, out, in article covers the modifiers in detail.

$ dotnet run
y = 10
numbers = [7, 8, 9]
q = 2, r = 2
False

Boxing

When a value type is assigned to a variable of type object or an interface, it is boxed: the value is copied into a new object on the heap.

Program.cs
int n = 5;
object boxed = n;

n = 6;
Console.WriteLine($"n = {n}, boxed = {boxed}");

object o1 = 42;
object o2 = o1;
Console.WriteLine(ReferenceEquals(o1, o2));

int unboxed = (int)o1;
unboxed++;
Console.WriteLine($"o1 = {o1}, unboxed = {unboxed}");

object a = 42;
object b = 42;
Console.WriteLine(a == b);
Console.WriteLine(a.Equals(b));

We box and unbox integers.

object boxed = n;

n = 6;

The box holds a copy of the value 5; changing n later does not change it.

int unboxed = (int)o1;
unboxed++;

Unboxing copies the value out of the box again. The box itself is not modified.

Console.WriteLine(a == b);
Console.WriteLine(a.Equals(b));

Two boxes with the same value are two different objects. On object variables, the == operator compares references and returns false; Equals compares the values.

$ dotnet run
n = 6, boxed = 5
True
o1 = 42, unboxed = 43
False
True

Structs in collections

Copy semantics cause a common surprise with structs stored in collections.

Program.cs
List<Point> points = [new(1, 2), new(3, 4)];

// points[0].X = 10;  // error CS1612

Point p = points[0];
p.X = 10;
Console.WriteLine(points[0]);

points[0] = p;
Console.WriteLine(points[0]);

Point[] arr = [new(1, 2), new(3, 4)];
arr[0].X = 10;
Console.WriteLine(arr[0]);

foreach (var pt in arr)
{
    // pt.X = 0;  // error CS1654
    Console.WriteLine(pt.X);
}

struct Point(int x, int y)
{
    public int X = x;
    public int Y = y;

    public override readonly string ToString() => $"({X}, {Y})";
}

We try to modify points in a list and in an array.

// points[0].X = 10;  // error CS1612

The indexer of List<T> is a method that returns a copy of the element. Modifying a field of that temporary copy would have no effect, so the compiler rejects it with "error CS1612: Cannot modify the return value of 'List<Point>.this[int]' because it is not a variable".

Point p = points[0];
p.X = 10;
Console.WriteLine(points[0]);

points[0] = p;

We must take a copy, change it, and store it back.

arr[0].X = 10;

Array elements are variables, so an array element can be modified in place. The foreach iteration variable is a read-only copy, and modifying it is the CS1654 error. These pitfalls are one reason why structs are best made immutable, for example with readonly struct.

$ dotnet run
(1, 2)
(10, 2)
(10, 2)
10
3

Summary

The main points of the article:

Source

Value types - C# reference

Reference types - C# reference

Method parameters - C# reference

In this article we have explained copy by value and copy by reference in C#. See also the struct, class, ref, out, in, and shallow & deep copy tutorials.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.