Skip to content

When to use struct vs class

Context: Choosing between struct and class depends on the intended use, size, and behavior requirements.

  • The instance is small (≤ 16 bytes typically)
  • The type is immutable (or should have value semantics)
  • You need value equality (copies are independent)
  • Performance requires stack allocation (e.g., many short‑lived instances)
  • The type is used in performance‑critical paths
  • The type is large (> 16 bytes)
  • You need reference semantics (sharing, identity)
  • Inheritance is required
  • You need to use the type with null checks (reference types)
  • The object will be stored in collections frequently (boxing overhead for structs)
FeatureStructClass
TypeValue typeReference type
AllocationStack / inlineHeap
InheritanceNo (except interfaces)Yes
Default equalityValue‑basedReference‑based
NullableNullable<T> or T?Directly null
// Good struct candidate: small, immutable, value semantics
public readonly struct Point(int X, int Y);
// Good class candidate: large, mutable, needs identity
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
// ...
}

Database entities: Use classes because they have identity (database primary key) and are often large. Value objects (like Money, Address) are better as structs or records.

Example: In Entity Framework Core, entities are classes. Value objects can be implemented as struct or record struct.