Struct best practices - rianjs/DotNetPerfTesting GitHub Wiki

Guiding principles

  • Use structs to represent single notions that require strong typing. Examples: routing numbers, IBAN numbers, coordinates, etc.
  • Make them immutable and therefore readonly
    • Most types that are used to represent elements of your domain should be immutable whenever possible
  • Implement IEquatable<T>, and implement the == and != operators
  • Implement IComparable<T> if the value has a natural ordering
  • Most properties should be representable as the application of a function to the underlying value. Or in C# terms: "get-only properties".
    • For example, a banking institution's canonical identifier is part of it's routing number, so this property is defined as: public string AbaInstitutionIdentifier => RoutingCode.Substring(4, 7);

Struct size

The performance rule of thumb is to keep your structs to 16 bytes (128 bits) or less for regular structs. Regular in this case means non-ref, non-readonly, and not passed with in.

  • In a 64-bit application, references require 8 bytes (64 bits)
    • 2 references fit inside a struct on a 64-bit machine
  • In a 32-bit application, references require 4 bytes (32 bits)
    • 4 references fit inside a struct on a 32-bit machine