skip to content

In C#, when should you declare a type as a struct rather than a class, and when is a class the better choice?

level: juniorimportance: must knowfreq 78%

answer

  1. one small logical value
  2. immutable after construction
  3. all-zero default must be valid
  4. rarely boxed, no inheritance
  5. class is the default

basics

~20 s

Choose a struct for a small, immutable type that represents one logical value, stays valid when all-zero and is rarely boxed, such as a coordinate or a timestamp. Choose a class for identity, inheritance, or large or changing state.

solid answer

~40 s

A C# `struct` is a value type: assignment, passing an argument and returning a result copy the whole instance, and its `default` has every field zeroed. That suits small values such as `DateTime`, `TimeSpan` or the 12-byte `System.Numerics.Vector3`, which sit inline in arrays and in the objects that contain them with no allocation of their own. Microsoft's Framework Design Guidelines say to avoid a struct unless the type represents a single value, is under 16 bytes, is immutable and will not be boxed frequently. Everything else defaults to a class: entities with identity, types that need inheritance, large or changing state, and types used mostly as `object` or through an interface. Declaring the struct `readonly` turns the immutability advice into a compiler check.

go deeper

for a junior

Recall the four traits from the design guidelines: one logical value, under 16 bytes, immutable, rarely boxed. Name a BCL struct such as DateTime and say why it fits.

for a middle

Explain what copy-on-assignment and the zeroed default mean for a struct, and why a mutable or large struct causes surprises a class would not.

for a senior

Review a struct someone added for speed: ask for the size, how often it is copied or boxed, whether its zeroed state is valid, and whether profiling ever showed allocation as the cost.

for a principal

Frame struct versus class as a default plus justified exceptions, and weigh the copying and zero-state risks against the allocation savings in hot code.

## What a struct is in C# A **struct** declares a **value type**. A variable of a struct type holds the instance itself, not a reference to it, so an assignment, an argument and a return value each copy the whole instance. A **class** declares a **reference type**: the variable holds a reference, and copying the variable copies only that reference. How copying and sharing play out line by line is the lesson on copying vs sharing; this answer is about choosing between the two. Two consequences drive the choice: - A struct needs no heap allocation of its own. A struct local, a struct field inside a class and the elements of a struct array are stored **inline**, so an array of 10,000 small structs is one allocation, where an array of 10,000 class instances is 10,001. - Every copy costs the full size of the struct. Copying an 8-byte `DateTime` is as cheap as copying a reference; copying a 2 KB value on every call is not. ## The checklist in the design guidelines Microsoft's **Framework Design Guidelines** (the 2008 edition the .NET docs still reprint, with a note that some of it may be out of date) say to **consider** a struct when instances are small and commonly short-lived or embedded in other objects, and to **avoid** a struct unless the type has all of these traits: 1. It logically represents a **single value**, like `int` or `double`. 2. Its instance size is **under 16 bytes**. 3. It is **immutable**. 4. It will not have to be **boxed** frequently. | Concern | struct | class | |---|---|---| | Assignment and arguments | copy the whole value | copy a reference | | Default value | every field zeroed | `null` | | Inheritance | none; may implement interfaces | one base class, virtual members | | Storage | inline in its container | a separate heap object | | Finalizer | not allowed | allowed | | Conversion to `object` or an interface | boxes a copy | no conversion cost | The 16-byte figure is a rule of thumb, not a compiler limit: the BCL itself ships 16-byte structs such as `Guid` and `decimal`. The other three traits matter more, because breaking them causes bugs rather than mere slowness. ## Default zeroing is part of the contract Every struct has a value nobody constructed. `default(T)`, the elements of `new T[n]` and an unassigned struct field inside a new class instance all hold the **all-zero bit pattern**: numbers are 0, `bool` is `false`, references are `null`. The struct design guidelines say to make sure that state is valid. A `Money` struct whose zeroed `Currency` string is `null` fails with a `NullReferenceException` far from the line that created the array; a `DateTime` whose default is 1 January 0001 is odd but still valid. If no sensible all-zero value exists, the type probably wants to be a class. Why a parameterless constructor does not rescue this is a separate question on this page. ## Where a class wins Choose a class when any of these holds: - The type has **identity**: two orders with the same lines are still two orders. - It needs **inheritance** or virtual dispatch from a base type; a struct derives implicitly from `System.ValueType` and can be no type's base. - Its state **changes over its lifetime** and several parts of the program must see the change; a mutable struct quietly edits copies. - It is **large**, so copies cost more than the allocation they save. - It is handled mostly as `object` or through an interface, so it would be **boxed** constantly; where boxing happens is the boxing lesson's subject. ## Worked example: a game-loop vector and a 2 KB sensor reading A gameplay loop moves thousands of particles per frame, each positioned by three `float` values. A 12-byte vector struct fits well: it is one logical value, an array of them is one contiguous block with no per-element allocation, and its zeroed default, the origin, means something. .NET's own `System.Numerics.Vector3` is such a 12-byte struct. Now a teammate turns a 2 KB sensor-reading type into a struct "for speed". Every assignment, every call that takes it by value and every `foreach` iteration now copies 2 KB; a `List<T>` of them copies each reading in and out through its indexer; and an all-zero reading is probably not a real reading. Unless profiling showed the allocation was the bottleneck and the code avoids copying, a class is the better design. A quick test for review: if you are happy for the value to be copied freely, compared field by field and created zeroed, it can be a struct; if any of the three bothers you, make it a class.

  • Is the 16-byte guideline a hard rule in C#?
    No. The compiler accepts a struct of any size; the figure comes from the 2008 Framework Design Guidelines, which the .NET docs reprint with a note that parts may be out of date. It approximates where copying a value starts to cost more than passing a reference. The BCL ships 16-byte structs such as `Guid` and `decimal`. Treat a larger struct as a choice to justify with measurements, and avoid copying it.
  • Why must a struct be valid when all of its fields are zero?
    Because C# creates zeroed instances without running any constructor: `default(T)`, the elements of `new T[n]` and struct fields of a newly created class all start as the all-zero bit pattern. If zero means invalid, such as a `null` currency code or a range with zero length that a method divides by, those instances fail later, far from where they were made.
  • What does declaring the struct `readonly` add?
    `readonly struct` (C# 7.2) makes the compiler require every field to be `readonly` and every property to be get-only or init-only, so no member can modify the instance after construction. It turns the guideline that structs should be immutable into a compile-time check, and it lets the compiler skip the hidden copies it otherwise makes when a member is called on read-only storage.

  • Structs are always faster than classes, so use them wherever performance matters.
  • A type that holds only data should be a struct, whatever its size.
  • A struct can inherit fields from a base struct.
  • The default value of a struct variable is null, like a class.
  • Struct size does not matter because copying is free.