Struct vs. class

Structs seem to be largely ignored in .NET. Everyone uses them (Int32 is pretty common!), but rarely pay attention to the fact that they're structs instead of classes, and rarely need to. I've worked on several projects where I don't think a single custom struct was defined. A good .NET/C# programmer should understand the differences between classes and structs as they consume them, but when creating a new type, most folks just create a class without a second thought (a class is usually the right answer anyway).

I came across a case where a new type was created, mostly for use in custom database access code, to represent a composite database key. My first thought was that a struct was more appropriate; conceptually, it's a single "value" that uniquely identifies the data, it would be created and consumed and compared with all properties assigned, and is small and not expected to grow. Microsoft has guidance on when to create a struct or a class, and it met all the requirements but one:

  • It has an instance size under 16 bytes.

This key had 3 ints & 2 int-based enums, for a total of 20 bytes. That's close enough to 16, right? That's not a hard-and-fast rule, is it? Some research brought me to analysis & testing results from Stack Overflow user Göran Andersson, who found the compiler treats structs differently when they cross the 16 byte threshold (at least in the .NET 4.0 timeframe).

It helps to understand the docs didn't just pick 16 bytes as an arbitrary breaking point. I'd be curious to know if versions of the compiler(s) released in the 7 years since have changed this behavior--one user claims it's grown to 20 bytes for x86 and 24 bytes for x64 as of 2014--but those performance tests will have to wait for now.

1 Comment

Comments have been disabled for this content.