Value types and reference types
Two kinds of type
Every C# type is one of two kinds, and the difference is what an assignment does.
- A value type holds its data in the variable. The built-in numbers, char, bool, an enum and a struct are value types. An assignment copies the data, and the two variables are then independent.
- A reference type holds an address. A class, an interface, an array, a string and a record are reference types. An assignment copies the address, and the two variables then name the same object.
The next two sections show both with the same fields, so the only difference is the keyword.
A copy and a reference
var pointA = new Point { X = 1, Y = 2 };
var pointB = pointA;
pointB.X = 99;
Console.WriteLine($"struct: {pointA.X} {pointB.X}");
var boxA = new Box { X = 1, Y = 2 };
var boxB = boxA;
boxB.X = 99;
Console.WriteLine($"class: {boxA.X} {boxB.X}");
struct Point
{
public int X;
public int Y;
}
class Box
{
public int X;
public int Y;
}
dotnet run
struct: 1 99
class: 99 99
The struct line proves the copy: pointB started as a
copy of pointA, so writing 99 into one left the other
at 1. The class line proves the sharing:
boxB is another name for the same object, so 99 is
visible through both.
Two consequences follow. A method that takes a struct gets a copy and cannot
change the caller value, and a method that takes a class gets the same
object and can. The lesson on
ref, out and in shows the
keyword that passes a struct by reference instead.
The type at run time
Every value knows its type, and GetType() returns it. A boxed value type and a reference type answer the same way:
object[] values = { 42, 3.5, "text", 'c', true };
foreach (var value in values)
{
Console.WriteLine($"{value} is {value.GetType().Name}");
}
Console.WriteLine($"and {values.Length} values in all");
dotnet run
42 is Int32
3.5 is Double
text is String
c is Char
True is Boolean
and 5 values in all
The array is an object[], so each number was
boxed: wrapped in an object to be stored next to the strings. The
box remembers the type of the value it holds, which is why the number
reports Int32 and not
Object. The lesson on
boxing measures what that
wrapper costs.
GetType(), typeof and the
difference between the two are the subject of
how to find out the type of a C# variable,
which reads the same question from the side of reflection.
Which one to use
A class is the default: it is a reference, it may be
null, it is inherited from and it is allocated on the
managed heap. A struct is for a small value that behaves like a number: two
or three fields, no identity, no inheritance, and a copy that is cheap.
DateTime, TimeSpan,
Guid and decimal are structs
of the BCL for that reason.
A big struct is a trap: every assignment copies all of it, and a struct in
an array is copied out on each read. The part on
structs shows
readonly struct and
ref struct, and the lesson on
struct against class
measures the difference.
Exercises
- Change Point from a struct to a class and run the first program again. Which line changes, and why?
- Pass a Point to a method that sets X = 99. Does the caller see it? Then do the same with Box.
- Remove object[] and write var values = new[] { ... } with the same five values. Which error does the compiler give, and what does that say about the types?
- Print typeof(int) and 42.GetType(). Are the two results the same object?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does an assignment of one struct variable to another copy?
Answer
The data of the struct, so the two variables are independent
A value type lives in the variable, and an assignment copies all of its fields; a class would copy only the address.
-
Which of these is a reference type?
Answer
string
string is a class; int, DateTime and decimal are structs, which is why a string can be null and a decimal cannot.
-
What does this program print?
var a = new Point { X = 1 }; var b = a; b.X = 5; Console.WriteLine(a.X); Console.WriteLine(b.X); struct Point { public int X; }Answer
1 / 5
The struct is copied on assignment, so changing b leaves a at 1.
-
What does this program print?
var a = new Box { X = 1 }; var b = a; b.X = 5; Console.WriteLine(a.X); Console.WriteLine(b.X); class Box { public int X; }Answer
5 / 5
b is another reference to the same object, so the write through b is visible through a.
-
What does this program print?
Console.WriteLine(42.GetType().Name); Console.WriteLine("42".GetType().Name);Answer
Int32 / String
The literal 42 is an int and the literal "42" is a string, and GetType reports the type of the value.
-
What is boxing?
Answer
Storing a value type in an object, which wraps it on the heap
An object variable cannot hold an int directly, so the runtime allocates a box that carries the value and its type.
-
What does this program print?
object value = 3; Console.WriteLine(value.GetType().Name);Answer
Int32
The int is boxed into the object, and the box keeps the type of the value it holds.
-
Why are DateTime and Guid structs rather than classes?
Answer
They are small values with no identity, and a copy is cheap
A date or a GUID is a value: two equal dates are interchangeable, and a copy of a few bytes costs less than a heap object.
-
What does this program print?
var p = new Point(); Change(p); Console.WriteLine(p.X); static void Change(Point point) => point.X = 7; struct Point { public int X; }Answer
0
The method gets a copy of the struct, so the write changes the copy and the caller keeps 0.
-
Which statement about a string is true?
Answer
It is a reference type whose value cannot change, so a method such as ToUpper returns a new string
A string is immutable: no method can change it, and every transformation returns another string.
The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev