Conceptcore
Value types and reference types
Also called value type, reference type, value semantics, reference semantics, struct versus class, primitive types and reference types, call by sharing.
A variable of a value type holds the value, so assignment copies it. A variable of a reference type holds a reference, so assignment shares one object between two names.
- Applies to
- core-languages
Idea
When a program assigns one variable to another, it can copy the value, or it can copy a reference to one shared object. A value type gives the first behavior and a reference type gives the second. The difference decides what a change through one variable does to the other, what == compares, and what a function can change in its caller. C# has both kinds side by side: a struct is a value type and a class is a reference type.
using System;
var s1 = new PointS { X = 1 };
var s2 = s1; // copies the whole struct
s2.X = 9;
var c1 = new PointC { X = 1 };
var c2 = c1; // copies the reference
c2.X = 9;
Console.WriteLine($"struct: {s1.X} {s2.X}");
Console.WriteLine($"class: {c1.X} {c2.X}");
Console.WriteLine($"{s1.Equals(new PointS { X = 1 })} {c1.Equals(new PointC { X = 9 })} {ReferenceEquals(c1, c2)}");
struct PointS
{
public int X;
}
class PointC
{
public int X;
}
struct: 1 9
class: 9 9
True False True
PointS and PointC have the same field. The assignment s2 = s1 copies the struct, so the change to s2 leaves s1 as it was. The assignment c2 = c1 copies the reference, so c1 and c2 name one object, and the change shows through both. The default Equals of a struct compares the fields, and the default Equals of a class compares identity, so a second object with the same field is not equal to c1.
How it works
What a variable holds. "In certain computer programming languages, data types are classified as either value types or reference types, where values referenced by reference type variables are always implicitly accessed via references stored in those variables, whereas value type variables directly contain the values themselves"1. In C#, "A variable of a value type contains an instance of the type. This behavior differs from a variable of a reference type, which contains a reference to an instance of the type"2.
Copying. "Assigning to a variable of reference type simply copies the reference, whereas assigning to a variable of value type copies the value"1. The same rule holds for a call: "parameters of reference type are copies of the reference, whereas parameters of value type are copies of the value"1. So "If a reference type is mutable, then mutations made via one reference are visible via any other"1.
Identity and equality. "Reference types support the notion of identity"1: two references can point to one object or to two objects with equal contents, and the language can tell these cases apart. A value of a value type has no identity of its own, so equality compares the contents. See value equality and identity.
Call by sharing. Java passes every argument by value, and C# does so by default, but the value of a reference type is a reference, so a function that changes the object changes it for the caller too. "This behavior is sometimes called call by sharing"1. Call by sharing is not call by reference: when a function assigns another object to its parameter, "this assignment will not be visible to the caller, because the caller and the function have separate references, even though both references initially point to the same object"1. See parameter passing.
How languages split the types. In Java, "There are, correspondingly, two kinds of data values that can be stored in variables, passed as arguments, returned by methods, and operated on: primitive values (§4.2) and reference values (§4.3)"3, and "The reference values (often just references) are pointers to these objects, and a special null reference, which refers to no object"3. In JavaScript, "a primitive (primitive value, primitive data type) is data that is not an object and has no methods or properties"4, and objects are shared by reference. In Python, every value is an object, and "Every object has an identity, a type and a value"5, so every variable holds a reference; immutable objects such as numbers, strings and tuples act like values because no one can change them.
Values with explicit pointers. C, C++, Go and Rust treat every type as a value type and make sharing explicit with pointers or references. In Go, "everything in Go is passed by value", and "passing a pointer value makes a copy of the pointer, but not the data it points to"6. But "Map and slice values behave like pointers: they are descriptors that contain pointers to the underlying map or slice data"6. In Rust, a type that implements Copy is one whose values "can be duplicated simply by copying bits"7, and other types move on assignment. In C++, a reference is "an alias to an already-existing object or function"8, and once bound it cannot be bound to another object, so it is not a reference type in the sense of this page1.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Idiom | |
| C++ | Idiom | |
| Java | Native | |
| C | Idiom | |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | TypeScript has the same split as JavaScript; primitives are copied and objects are shared. No example file exists. |
| Go | Idiom | |
| Rust | Idiom | |
| Kotlin | Native | Classes are reference types, and the basic types such as Int act as values. No example file exists because kotlinc is not installed. |
| SQL | Does not apply | A query works on values in rows, and SQL has no references between variables. |
| Bash | Does not apply | Every Bash variable holds a string, and assignment copies it, so there are no references between variables. |
| PowerShell | Native | PowerShell uses the .NET value types and reference types, as in C#. No example file exists because pwsh is not installed. |
| HTML | Does not apply | HTML has no variables. |
| CSS | Does not apply | CSS custom properties hold values, not references. |
| Regular expressions | Does not apply | A regular expression has no variables. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | idiom | every variable holds a reference to an object; immutable types such as int, str and tuple act like values |
| JavaScript | native | primitives such as numbers and strings are values; objects, arrays and functions are shared by reference |
| TypeScript | native | the same split as JavaScript; readonly types limit changes but not sharing |
| Java | native | primitive types such as int are values; classes, interfaces and arrays are reference types |
| Kotlin | native | classes are reference types; the basic types such as Int and Double are immutable values |
| C# | native | struct, enum and the numeric types are value types; class, interface, delegate and arrays are reference types |
| Go | idiom | all types are values, including arrays and structs; pointers share; maps, slices and channels hold internal pointers |
| Rust | idiom | all types are values that move or copy; &T, &mut T, Box, Rc and Arc share |
| C | idiom | all types are values, including structs; pointers share; an array argument becomes a pointer |
| C++ | idiom | all types are values with copy constructors; pointers and smart pointers share; a reference is an alias |
| Bash | n/a | every variable holds a string, and assignment copies it |
| PowerShell | native | .NET value types and reference types, as in C# |
| SQL | n/a | a query works on values in rows; there are no references between variables |
| Regex | n/a | a pattern has no variables |
| HTML | n/a | HTML has no variables |
| CSS | n/a | custom properties hold values, not references |
C#, Java, JavaScript and Kotlin give each type one kind of behavior, and the programmer chooses it when they declare the type. C, C++, Go and Rust make every type a value type and let the programmer choose sharing at each use, with a pointer or a reference. Python makes every type a reference type and gets value behavior from immutable objects.
The example files show these differences. Python shows that a list is shared and that [[0] * 3] * 3 repeats one inner list. JavaScript shows that structuredClone makes a deep copy. Java shows that a method can change an object it receives but cannot rebind the caller's variable. C# shows that a struct read from a List is a copy. Go shows that an array and a struct are copied while a slice and a map share their data. Rust shows Copy, a move and clone. C shows that a struct assignment copies the whole struct. C++ shows copies, a reference that is an alias, and a shared_ptr that shares.
a = [1, 2, 3]
b = a # copies the reference, not the list
b.append(4)
print(a, a is b)
c = list(a) # a shallow copy is a new list
c.append(5)
print(a, c, a is c)
grid = [[0] * 3] * 3 # three references to one inner list
grid[0][0] = 1
print(grid)
grid = [[0] * 3 for _ in range(3)] # three inner lists
grid[0][0] = 1
print(grid)
n = 1
m = n
m += 1 # an int cannot change, so += binds m to another object
print(n, m)
[1, 2, 3, 4] True
[1, 2, 3, 4] [1, 2, 3, 4, 5] False
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]
[[1, 0, 0], [0, 0, 0], [0, 0, 0]]
1 2
- Verdict: idiom. Every Python variable holds a reference, so
b = amakes two names for one list, and a change throughbshows througha.[[0] * 3] * 3repeats the reference to one inner list, so a change to one row changes all three. Anintcannot change, som += 1makesmrefer to another object andnkeeps its value; this is why immutable types act like value types.
#include <iostream>
#include <memory>
#include <vector>
int main() {
std::vector<int> a{1, 2};
std::vector<int> b = a; // copies the elements
b.push_back(3);
std::cout << a.size() << " " << b.size() << "\n";
std::vector<int>& r = a; // r is another name for a
r.push_back(9);
std::cout << a.size() << " " << &r[0] - &a[0] << "\n";
auto p = std::make_shared<std::vector<int>>(std::vector<int>{1});
auto q = p; // shares one vector and counts the owners
q->push_back(2);
std::cout << p->size() << " " << p.use_count() << "\n";
}
2 3
3 0
2 2
- Verdict: idiom. A
std::vectoris a value: its copy constructor copies the elements, sobchanges alone. A reference is an alias, so a change throughris a change toa. Astd::shared_ptrshares one object between owners and counts them.
import java.util.ArrayList;
import java.util.List;
public class Main {
static void addItem(List<String> list) {
list.add("b"); // changes the object that the caller also sees
}
static void replace(List<String> list) {
list = new ArrayList<>(); // rebinds only the parameter
list.add("z");
}
static void bump(int n) {
n++; // changes only the copy
}
public static void main(String[] args) {
List<String> items = new ArrayList<>(List.of("a"));
addItem(items);
replace(items);
System.out.println(items);
int count = 1;
bump(count);
System.out.println(count);
List<String> other = new ArrayList<>(List.of("a", "b"));
System.out.println((items == other) + " " + items.equals(other));
}
}
[a, b]
1
false true
- Verdict: native. A
Listis a reference type, soaddItemgets a copy of the reference and changes the caller's list.replaceassigns another list to its parameter, and the caller does not see that. Anintis a primitive type, sobumpchanges only its copy.==compares references, andequalscompares the contents.
#include <stdio.h>
struct point {
int x;
int tags[2];
};
static void bump(struct point p) { p.x++; }
static void bump_ptr(struct point *p) { p->x++; }
int main(void) {
struct point a = {1, {10, 20}};
struct point b = a; /* copies every member, the array too */
b.x = 9;
b.tags[0] = 99;
printf("%d %d %d %d\n", a.x, a.tags[0], b.x, b.tags[0]);
bump(a); /* the function gets a copy */
printf("%d\n", a.x);
bump_ptr(&a); /* a pointer shares */
printf("%d\n", a.x);
return 0;
}
1 10 9 99
1
2
- Verdict: idiom. C copies a struct on assignment and on a call, including an array member of the struct. A function that must change the caller's struct takes a pointer.
using System;
using System.Collections.Generic;
var points = new List<PointS> { new PointS { X = 1 } };
var p = points[0]; // the indexer returns a copy
p.X = 9;
Console.WriteLine($"{points[0].X} {p.X}");
points[0] = p; // write the changed copy back
Console.WriteLine(points[0].X);
var boxes = new List<PointC> { new PointC { X = 1 } };
var c = boxes[0]; // a copy of the reference
c.X = 9;
Console.WriteLine(boxes[0].X);
Move(ref p);
Console.WriteLine(p.X);
static void Move(ref PointS q) => q.X += 1;
struct PointS
{
public int X;
}
class PointC
{
public int X;
}
1 9
9
9
10
- Verdict: native.
PointSis a struct, so readingpoints[0]gives a copy, and the change topdoes not reach the list until the code writespback.PointCis a class, soboxes[0]gives a reference, and the change shows through the list. Arefparameter passes the variable itself, soMovechanges the caller's struct.
let x = 1;
let y = x; // a primitive is copied
y = 2;
console.log(x, y);
const a = { name: "Ann", tags: ["admin"] };
const b = a; // an object is shared
b.name = "Bob";
console.log(a.name, a === b);
const shallow = { ...a }; // copies the top level only
shallow.tags.push("dev");
console.log(a.tags.join(","), shallow === a);
const deep = structuredClone(a); // copies every level
deep.tags.push("ops");
console.log(a.tags.join(","), deep.tags.join(","));
1 2
Bob true
admin,dev false
admin,dev admin,dev,ops
- Verdict: native. A number is a primitive, so
y = xcopies it. An object is shared, sob = agives two names for one object. Spread syntax makes a shallow copy: the top-level object is new, but thetagsarray is still shared.structuredClonemakes a deep copy, so a change to its array does not reach the original.
package main
import "fmt"
type Point struct{ X, Y int }
func main() {
arr := [3]int{1, 2, 3}
arr2 := arr // copies the whole array
arr2[0] = 9
fmt.Println(arr, arr2)
p := Point{1, 2}
q := p // copies the struct
q.X = 9
fmt.Println(p, q)
s := []int{1, 2, 3}
s2 := s // copies the slice header, which points to the same array
s2[0] = 9
fmt.Println(s, s2)
m := map[string]int{"a": 1}
m2 := m
m2["a"] = 9
fmt.Println(m["a"])
ptr := &p // a pointer shares explicitly
ptr.X = 7
fmt.Println(p)
}
[1 2 3] [9 2 3]
{1 2} {9 2}
[9 2 3] [9 2 3]
9
{7 2}
- Verdict: idiom. Every Go type is a value type, so assigning an array or a struct copies it. A slice and a map are small descriptors that hold a pointer to their data, so a copy of one shares the data. A pointer makes sharing explicit.
#[derive(Debug, Clone, Copy)]
struct Point {
x: i32,
}
fn main() {
let a = Point { x: 1 };
let mut b = a; // Point is Copy, so this copies the bits
b.x = 9;
println!("{:?} {:?}", a, b);
let s = String::from("hi");
let t = s; // String is not Copy, so this moves it
// println!("{}", s); // error: s was moved
println!("{}", t);
let mut u = t.clone(); // clone makes a second string
u.push('!');
println!("{} {}", t, u);
let mut v = vec![1, 2];
let r = &mut v; // a reference shares explicitly
r.push(3);
println!("{:?}", v);
}
Point { x: 1 } Point { x: 9 }
hi
hi hi!
[1, 2, 3]
- Verdict: idiom. Every Rust type is a value type.
PointimplementsCopy, so assignment copies it.Stringowns heap memory and is notCopy, so assignment moves it, and the compiler rejects a later use ofs.clonemakes an independent copy. A reference such as&mut vis the explicit way to share.
Variations and related ideas
- Value objects in Java. JEP 401 would "Introduce value objects, which are immutable and lack object identity. Value objects are distinguished solely by the values of their fields"9. It is a preview feature, and it keeps "just two kinds of data: primitives and object references"9.
- Immutable reference types. A reference type whose objects cannot change, such as
Stringin Java orstrin Python, behaves like a value type in most code, because sharing cannot be seen. See immutability. - Boxing. C# and Java convert a value to an object when the program needs a reference type, for example to store an
intin aList<Object>. See top type. - Explicit pointers. "Many languages have explicit pointers or references. Reference types differ from these in that the entities they refer to are always accessed via references"1. See pointers and references.
Pitfalls
- Calling value types stack types. A value type is not a type whose values live on the stack. Eric Lippert wrote that "value types are allocated on the stack sometimes", and that "the memory for an integer field in a class type is part of the class instance"10. The useful fact about a value type is "that they are always copied" by value10. See the stack and the heap.
- Changing a copy. In C#, reading a struct from a
List<T>gives a copy, so a change to that copy does not change the list. The C# example shows this. Make structs immutable, or use a class when the program must change a shared object. - Unexpected sharing. "If a reference type is mutable, then mutations made via one reference are visible via any other"1. A list that two parts of a program share can change under one of them. Copy the object at the boundary, or make it immutable.
- Rebinding a parameter. A function that assigns a different object to its parameter does not change the caller's variable1. Return the new object, or change the existing one.
- Object slicing in C++. Because C++ copies objects by value, "use of non-references can lead to problems such as object slicing, at least when inheritance is used"1. Copying a derived object into a base class variable drops the derived part. Pass such objects by reference or by pointer.
Cost
A value type costs a copy on each assignment and call, and the cost grows with the size of the value. A reference type costs one allocation for the object and one indirection on each access, and the copy of a reference is small. In C#, converting a value to object boxes it: boxing "allocates an object instance on the heap and copies the value"11. Lippert notes that, for value types, "the relevant thing is their copying and identity semantics"10, not where they are stored. JEP 401 aims to let a JVM represent immutable data "in ways that improve memory footprint, locality, and garbage collection efficiency"9.
History
The Java Language Specification divides the types into primitive types and reference types3, and C# lets a program declare its own value types with struct2. In 2009, Eric Lippert argued that the C# documentation should explain value types by copying, not by the stack10. JEP 401 proposes value objects for Java, which would let a class give up identity9.
References
- Value type and reference type, Wikipedia, Introduction; Properties of value types and reference types; Reference types and call by sharing; Reference types vs. explicit pointers
- Value types, C# language reference, Introduction
- The Java Language Specification, Java SE 25 Edition, Chapter 4, Introduction; 4.3.1 Objects
- Primitive, MDN Web Docs Glossary, Whole entry
- Data model, The Python Language Reference 3.14, 3.1 Objects, values and types
- Frequently Asked Questions, The Go Programming Language, When are function parameters passed by value?
- Trait Copy, The Rust Standard Library, Description
- Reference declaration, C++ reference, cppreference.com, Introduction; Explanation
- JEP 401, Value Objects (Preview), OpenJDK, Summary; Goals; Non-Goals
- The Stack Is An Implementation Detail, Part One, Eric Lippert, 2009, Whole post
- Boxing and Unboxing, C# programming guide, Boxing
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag CAMQ1D Edit this page History Report an error Markdown