C# in Depth

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

Pair - class or struct?

Chapter 3: Parameterized typing with generics: 3.3.3

Created: 1/29/2008
Last updated: 1/30/2008

The Pair type I included as listing 3.6 is implemented as a class. This made a lot of sense in early drafts where it was mutable - but it's a lot more sensible as an immutable type. For one thing, that means that the hashcode and equality operations will stay stable, so long as the values within the pair aren't mutable themselves.

At this point, however, you have to wonder - is there much point in it being a reference type? Why not make it a value type (a struct)? That way a pair of bytes is really cheap, for example.

I tend to default to writing classes rather than structs, but I'm beginning to think that generic types which end up just wrapping other values (based on type parameters) could often be better represented as structs. This is in line with various examples in the framework such as KeyValuePair<TKey, TValue>.