Glossary / Structs

Structs

A struct declares a value type whose assignment copies its fields and whose variables have value semantics. Structs can be mutable or immutable, implement interfaces, and contain methods and properties, but they cannot inherit from arbitrary classes. Choose them when copy semantics suit a small, self-contained value—not simply to avoid heap allocation.

Semantics and features

A struct always has a value even when default-initialized; its fields receive defaults unless constructors/required initialization establish other invariants. default(T) produces the default value. Structs can implement interfaces, but converting a struct value to an interface or object can box it. Struct fields can themselves be references, so copying a struct copies those references rather than deep-cloning their objects.

readonly struct and readonly members communicate immutability and can prevent defensive copies in some contexts. ref struct types, such as Span<T>, have restricted lifetimes and cannot be boxed or stored in ordinary heap objects; modern C# versions have expanded where they can be used, subject to compiler/runtime rules. record struct adds value-oriented equality and with support.

Large or mutable structs can be copied implicitly through parameters, returns, properties, or collection enumeration. A mutable struct accessed through a property may be a copy, so mutations can be lost. Use in, ref, or ref readonly only when justified and with careful lifetime/alias reasoning.

Design guidance

Prefer small, immutable structs with clear equality and no identity. Prefer classes for shared mutable state, inheritance, or large objects. Benchmark before optimizing; the GC may be cheaper than repeated copying or boxing. Document behavior of default values and equality.

Interview questions

  1. What does struct assignment do? Copies the struct's field values, including any contained references.
  2. Can structs implement interfaces? Yes; conversion may box, while generic constrained calls can avoid boxing.
  3. When can mutation disappear? When mutating a copy, such as a struct returned through a property.
  4. What is readonly struct for? Communicating immutable value semantics and helping avoid defensive-copy costs.
  5. Struct vs class? Value-copy semantics and no class inheritance versus reference identity, shared mutation, and polymorphism.

References