Glossary / Value types

Value types

A value type variable contains its value as part of the variable's storage, and assignment copies that value. Built-in numeric types, bool, char, enums, and structs are value types; nullable value types wrap a value type with an additional absent state. Value semantics affect copying and equality, but do not mean every value is physically stored on the stack.

Copying and storage

int a = 5;
int b = a;
b++;
// a is 5; b is 6

A struct assignment copies its fields. If a struct contains a reference-type field, the reference is copied, so both struct copies can still refer to the same referenced object. Value types can be fields inside heap objects, array elements, locals, or registers; the JIT and runtime determine physical storage subject to semantics. Avoid teaching “structs live on stack” as a rule.

Structs inherit from System.ValueType and cannot inherit from arbitrary classes, but can implement interfaces. Boxing converts a value to an object/interface representation and may allocate; unboxing checks and extracts a value. Large mutable structs can incur copying costs and surprising mutation behavior, especially through properties or interface calls.

Choosing and designing

Use structs for small, well-defined values where copy semantics are intuitive; consider readonly struct for immutable values and record struct for value-based equality. Use classes when identity, shared mutable state, polymorphic inheritance, or large data is central. Measure performance rather than selecting a struct solely to avoid allocations.

Interview questions

  1. What happens on assignment? The value is copied, including fields; nested references remain shared references.
  2. Are value types always on the stack? No; physical location depends on containing storage and JIT implementation.
  3. Can a struct implement an interface? Yes, though interface conversion can box unless optimized/avoided through generics.
  4. When is a struct a poor choice? Large, mutable, identity-oriented values that are frequently copied.
  5. What is boxing? Converting a value type to object or an interface representation.

References