Value types and reference types
Assigning a struct copies the data. Assigning a class instance copies only the reference to it.
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.The idea
A value-type variable holds the data itself. A reference-type variable holds an address of an object on the heap. So "copy" means two different things depending on the type.
Code
Point p1 = new Point { X = 1 };
Point p2 = p1; // copies the value
p2.X = 9;
Box b1 = new Box { X = 1 };
Box b2 = b1; // copies the reference
b2.X = 9;
Console.WriteLine(p1.X + " " + b1.X); // 1 9
struct Point { public int X; } // value type
class Box { public int X; } // reference typeclass Point { // Java has no structs: a value copy is made by hand
int x;
Point(int x) { this.x = x; }
Point(Point other) { this.x = other.x; }
}
class Box { // reference type
int x;
Box(int x) { this.x = x; }
}
public class Main {
public static void main(String[] args) {
Point p1 = new Point(1);
Point p2 = new Point(p1); // copies the value
p2.x = 9;
Box b1 = new Box(1);
Box b2 = b1; // copies the reference
b2.x = 9;
System.out.println(p1.x + " " + b1.x); // 1 9
}
}struct Point { int x; }; // a plain value: copying it copies the data
struct Box { int x; }; // shared through a pointer below to get reference behaviour
int main() {
Point p1{1};
Point p2 = p1; // copies the value
p2.x = 9;
auto b1 = make_shared<Box>(Box{1});
auto b2 = b1; // copies the reference (the pointer)
b2->x = 9;
cout << p1.x << " " << b1->x << "\n"; // 1 9
}from copy import copy
from dataclasses import dataclass
@dataclass
class Point: # Python has no value types: copy() stands in for a struct copy
x: int
@dataclass
class Box: # every Python object is a reference type
x: int
p1 = Point(1)
p2 = copy(p1) # copies the value
p2.x = 9
b1 = Box(1)
b2 = b1 # copies the reference
b2.x = 9
print(p1.x, b1.x) # 1 9Tips
- int, double, bool, char, DateTime, enums and every struct are value types. string, arrays, List<T> and every class are reference types.
- This is the root cause of most "why did my other variable change?" bugs.
In the .NET library
A record class is still a reference type, but it compares by value. A record struct is a value type. Choose struct only for small, immutable data.