Structs
A struct is a value
A struct is a value type: the variable holds the fields themselves, not a reference to an object on the heap. Assigning one to another copies every field, and the two variables are independent from that moment. A class does the opposite, as the lesson on classes showed.
var first = new Point(3, 4);
var second = first;
second.X = 10;
Console.WriteLine($"first {first.X},{first.Y} second {second.X},{second.Y}");
struct Point
{
public Point(int x, int y)
{
X = x;
Y = y;
}
public int X { get; set; }
public int Y { get; set; }
}
dotnet run
first 3,4 second 10,4
second changed and first did not, because the assignment copied two integers. That is the whole difference from the class version of the same program, which printed first 2 second 2 for one object.
readonly struct and default
A struct whose fields never change is best declared readonly struct: the compiler then refuses a set accessor and removes a copy the runtime would otherwise make when the struct is passed to a method that reads it.
var size = new Size(2, 3);
var copy = size;
var zero = default(Size);
Console.WriteLine(size);
Console.WriteLine($"copy equal {copy.Equals(size)}");
Console.WriteLine($"default {zero} area {zero.Area}");
readonly struct Size(int width, int height)
{
public int Width { get; } = width;
public int Height { get; } = height;
public int Area => Width * Height;
public override string ToString() => $"{Width}x{Height}";
}
dotnet run
2x3
copy equal True
default 0x0 area 0
new Size(2, 3) names the primary constructor, and the two property initialisers fill the read-only properties. default(Size) is a struct with every field zeroed: a value type has no null, so a default struct always exists and its area is 0. Equals compares the fields, which is the default for a struct, and the override of ToString is what makes the first line readable.
ref struct and the error
A ref struct may only hold references into the stack, which is what makes Span<T> free of allocation. The price is a set of restrictions, and the first one a reader meets is that such a type cannot be a field of a class: the object could outlive the stack frame the span points into.
var holder = new Holder();
Console.WriteLine(holder.Data.Length);
class Holder
{
public Span<int> Data;
}
dotnet build
Program.cs(6,12): error CS8345: Field or auto-implemented property cannot be of type 'Span<int>' unless it is an instance member of a ref struct.
Build FAILED.
Program.cs(6,12): error CS8345: Field or auto-implemented property cannot be of type 'Span<int>' unless it is an instance member of a ref struct.
0 Warning(s)
1 Error(s)
Time Elapsed 00:00:04.21
The message says where the span may live: in a field of another ref struct, which itself lives on the stack. The same rules forbid boxing a span, storing it in an object and holding it across an await; each of those would let the pointer outlive the memory it points at.
When a struct is the right choice
- Small data that behaves like a value: a point, a colour, a range, a money amount with its currency. A struct of a few fields is cheap to copy and needs no heap allocation.
- A type whose instances are short-lived and numerous, where the allocation of a class per item would dominate: this is why the BCL has DateTime, Guid and decimal as structs.
- Not for large data: a copy of a struct with twenty fields costs more than copying one reference, and every method call by value pays it.
- Not where identity matters: a struct has no reference to compare, and boxing it into an object to give it one defeats the purpose. The lesson on boxing measures that cost.
Exercises
- Change struct Point to class Point and run the first program again.
- Add an Add method to Point that returns a new point, and call it on a copy.
- Make Size a class and check what default(Size) becomes.
- Try to assign size.Width = 5 on the readonly struct and read the error.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does assigning one struct variable to another copy?
Answer
Every field of the value
A struct is a value type, so assignment copies the whole value.
-
What is
default(Size)for a struct?Answer
A value with every field at its default
A struct has no null; default gives the zeroed value.
-
What does this program print?
var a = new P { N = 1 }; var b = a; b.N = 2; Console.WriteLine(a.N + b.N); struct P { public int N { get; set; } }Answer
3
b is a copy, so b.N is 2 while a.N stays 1, and the sum is 3.
-
Why can a Span<int> not be a field of a class?
Answer
It may point into the stack, and the object could outlive that frame
CS8345 enforces the ref struct lifetime rule, which is what makes a span safe.
-
What does
readonly structprevent?Answer
Any assignment to its fields after construction
A readonly struct has only read-only state, and the compiler also avoids defensive copies.
-
What does this program print?
var s = new S(2); Console.WriteLine(s.Double); readonly struct S(int n) { public int Double => n * 2; }Answer
4
The primary constructor parameter is captured and read by the computed property.
-
Why is a struct a bad choice for a type with twenty fields?
Answer
Every copy and every call by value moves all twenty fields
A struct is copied by value, so a large one pays for the copy everywhere.
-
Which BCL type is a struct?
Answer
DateTime
DateTime, Guid and decimal are structs; string and the collections are classes.
-
What does
Equalsdo on a struct with no override?Answer
Compares the fields one by one
ValueType.Equals compares the fields of the two values, which is why copy equal printed True.
-
What is the cost of boxing a struct?
Answer
An allocation on the heap plus a copy of the value
Boxing wraps the value in a heap object so that an object reference can point at it.
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