Skip to content
Tutorials Center
My learning

Topics

Lesson 64 of 182 ยท Classes and Objects

Structs

Learn C# structs - copy semantics, struct vs class, constructors and default values, readonly structs, the mutable struct trap, record struct, ref struct and when to choose a struct.

A class is the default tool for modelling things in C#, but it is not the only one. A struct looks almost the same in source code, yet it behaves very differently: a struct variable contains its data instead of pointing to it, and assigning one struct to another copies every field. That one difference decides how structs are stored, compared, passed to methods and, sometimes, how fast your program runs.

You have already used structs without naming them: int, double, bool, char, DateTime, TimeSpan and Guid are all structs. This lesson shows how to write your own, the traps that catch even experienced developers (especially mutable structs), what readonly struct and record struct add, and how to decide between a struct and a class. It builds on value types and reference types and on classes.

Declaring a struct

The syntax mirrors a class. A struct can have fields, properties, methods, constructors, operators and can implement interfaces. It cannot inherit from another class or serve as a base class; it always derives from System.ValueType implicitly.

C# A first struct

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Changing b.X leaves a untouched, because b = a copied both fields. With a class Point the same code would change both variables, because they would share one object.

Notice the constructor: every field of a struct must be assigned before the constructor ends (since C# 11 the compiler fills in the missing ones with their default values automatically, but assigning them explicitly is clearer). Notice also that new Point(3, 4) does not necessarily allocate anything on the heap. It builds the value right inside the variable that receives it.

Copying is the whole story

Every time a struct is assigned, passed as an argument, returned from a method, or stored in a collection, the compiler copies its bytes. You can predict almost everything about structs from that single rule.

C# Copies when passing and storing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Bump incremented its own copy and the caller never noticed. BumpRef received a reference to the caller's variable (see parameters), so the change stuck. The array example shows an important detail: an array element is a storage location, so array[0].Value = 50 modifies the element in place. That is not true for every collection, as the next section shows.

The mutable struct trap

Mutable structs (structs whose fields can change after creation) are the classic source of confusing bugs. The compiler sometimes works on a temporary copy and the change disappears. Two cases come up constantly.

A property or indexer returns a copy

List<T>'s indexer is a method that returns an element. For a class that is a reference to the same object, so changing it works. For a struct, it returns a copy of the element. The compiler notices and refuses to let you modify the copy:

C# Modifying a copy from a list (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The compiler reports error CS1612: Cannot modify the return value of 'List<Counter>.this[int]' because it is not a variable. Good: the compiler stops you. The fix is to take the element out, change it, and put it back:

C#
var c = counters[0];
c.Value = 2;
counters[0] = c;

A method call on a readonly field works on a copy

The second trap is silent. If a struct is stored in a readonly field and you call a method that mutates it, the compiler makes a defensive copy first, so the method mutates the copy and your field never changes:

C# A silent defensive copy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The ordinary field reaches 2, the readonly field stays at 0, and nothing warns you. Two lessons follow from these traps:

  1. Prefer immutable structs. If a struct cannot change after construction, there is nothing to lose in a copy.
  2. If a struct must mutate, mark the mutating methods and treat the type as a small, private implementation detail rather than a public data model.

The .NET design guidelines say to avoid mutable value types for exactly this reason. A good test: if you cannot explain in one sentence why the type must be a struct, make it a class or a record.

readonly struct

Adding readonly to the declaration promises that no instance member modifies the struct. The compiler enforces it: all fields must be readonly (or get-only properties, init accessors are fine), and no method may assign to them.

C# A readonly struct

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

readonly struct has a performance benefit beyond safety. When you pass a struct with the in modifier (a read-only reference, see parameters) or store it in a readonly field, the compiler must otherwise copy it before every method call to protect it from mutation. For a type that is declared readonly, it knows no mutation can happen and skips those defensive copies.

You can also mark individual members readonly inside a non-readonly struct, for example public readonly double Length() => .... That tells the compiler this one method never changes this, which avoids a copy at the call site while leaving other members free to mutate.

Default values and constructors

Structs follow special rules about initialization, and they matter because you can never fully prevent someone from creating an "empty" one.

  • default(Point), new Point() (when there is no parameterless constructor you wrote), and every element of a freshly created Point[] are all-zero values: numbers 0, bool false, references null.
  • Since C# 10 you may declare your own parameterless constructor and field initializers. new Point() then runs it, but default(Point) and array elements still skip it and are all zeros.
  • Since C# 12 a struct may use a primary constructor.
C# Constructors do not run for default and arrays

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The output is 1, 0, 0. The consequence for design: a struct must treat the all-zero state as valid. If Money with a null currency would break your code, then guard against it or reconsider whether a struct fits. This is the reason DateTime has a valid default (January 1, year 1) and Guid.Empty exists.

Nullable and reference fields inside a struct work, but they weaken the "plain data" idea. A struct holding a string still copies only the pointer, so two copies share the same string object (harmless for immutable strings, surprising for a List<int> field).

Equality of structs

All structs get a default Equals from System.ValueType that compares the fields. It works, but it is slow: for structs that contain reference fields or unusual types it uses reflection, and calling it through object boxes the struct. Implement IEquatable<T> as the example above did, and override GetHashCode along with Equals (see the object class). If you do not want to write that by hand, use a record struct.

record struct and readonly record struct

C# 10 added record struct: you get the compiler-written value equality, ToString, with expressions and deconstruction of a record, but with value-type storage.

C# record struct versus readonly record struct

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Pay attention to one default that differs from record class: the positional properties of a plain record struct are mutable (get; set;), while a readonly record struct makes them init-only. Prefer readonly record struct unless you have a specific reason not to.

ref struct: a preview

A ref struct is a struct that can only live on the stack. It can never be boxed, stored in a field of a normal class, captured by a lambda, or used across an await. The famous example is Span<T>, a window onto a contiguous piece of memory:

C# Span is a ref struct

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Writing through the span changed the original array, because the span points at the same memory. Spans are covered properly in the memory and performance chapter (Span and Memory). For now remember that ref struct is how the language makes such safe-view types possible.

How big is a struct, and how fast?

A struct is copied on every assignment, so copying a large struct costs more than copying one reference. A struct is a good deal when it is small and short-lived: the Microsoft rule of thumb is "around 16 bytes or less". You can measure the size of a type with Unsafe.SizeOf:

C# Measuring struct sizes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The sizes are 4, 24 and 16 bytes. Padded holds 9 bytes of data but occupies 16, because the runtime aligns the long to an 8-byte boundary.

Arrays and lists of small structs are very cache friendly: the elements sit next to each other in one block of memory, with no per-object header and no pointer chasing. That is where structs shine in performance-sensitive code such as games, numerics and parsers.

When to use a struct, and when not to

Choose a struct when all of these hold:

  • It represents a single value logically, like a number, point, color, range or money amount.
  • It is small (about 16 bytes, rarely beyond 32).
  • It is immutable (readonly struct).
  • Its all-zero state is meaningful.
  • It is not frequently boxed (stored as object or in a non-generic collection).

Choose a class otherwise, especially for things that have identity, are large, change over time, or are shared between many holders. When in doubt, start with a class or a record: it is a safer default, and a measured performance problem is a better reason to change than a guess.

Structs do not make code automatically faster. Copies cost time, boxing allocates, and a large mutable struct passed by value can be slower than a class. Measure before you convert (see the performance lessons later in the course).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does Point b = a; do when Point is a struct?

    Assigning a struct copies its data, so afterwards a and b are independent. Sharing one object is what classes do.
  2. 2. Why does counters[0].Value = 2; not compile when counters is a List<Counter> and Counter is a struct?

    The compiler reports CS1612 because the list indexer returns a copy of the element. You must read, change and write back the element.
  3. 3. What is the value of Value for default(Level) if Level declares a parameterless constructor that sets it to 1?

    default(T) and array elements produce all-zero values without running any constructor, so the number stays 0.
  4. 4. Which declaration gives you a struct with value equality and immutable positional properties?

    A plain record struct has mutable properties. Adding readonly makes the positional properties init-only and the whole struct readonly.
  5. 5. Which type should usually be a class rather than a struct?

    Things with identity and changing state are shared between holders, which is what reference semantics are for.

Summary

  • A struct is a value type: assignment, argument passing and returning all copy its data.
  • Structs cannot inherit from classes, but they can implement interfaces; they derive from ValueType implicitly.
  • Mutable structs cause silent bugs (copies from list indexers, properties and readonly fields). Prefer readonly struct.
  • default(T) and arrays create all-zero structs without running constructors, so the zero state must be valid.
  • Implement IEquatable<T> and GetHashCode, or use readonly record struct, for fast value equality.
  • ref struct types such as Span<T> live only on the stack.
  • Use a struct for small, immutable, value-like data; use a class or record for everything else.

Next: Operator Overloading and Conversions