C# in Depth

Cover of C# in Depth
Order now (3rd edition)

When is it appropriate to write your own struct?

Chapter 2: Core foundations: building on C# 1: 2.3.3

Created: 4/4/2008
Last updated: 5/7/2008

In section 2.3.3 I talk a bit about the differences between structs and classes, but I don't give much guidance on when to use what.

In my experience, the "default correct choice" is to write classes. When it comes to immutable types, you could argue there's not a huge amount of difference between using a class and using a struct, beyond natural nullability and memory behaviour - but there's a difference in gut feeling.

By and large, I only write custom structs to represent some sort of basic quantity. For instance, I can imagine writing a Money struct which encapsulated the amount (as a decimal) and the currency (possibly an enum, or more likely a reference type with a small number of shared instances). I'd be very unlikely to encapsulate a person as a struct, or a collection.

There's more on this topic in the Microsoft design guidelines.

One important rule to avoid breaking: structs should almost always be immutable. Mutability in structs can cause horrific bugs which are really hard to track down. It's even worse if the mutability is available through an interface the struct implements. Just say no.