There was a recent question over an internal alias the clarify the struct usage guidelines and I thought you’d find that data helpful…. The API designer was confused about what 2 and 4 really mean.


1.       Act like primitive types

2.       Have an instance size under 16 bytes

3.       Are immutable

4.       Value semantics are desirable.


Have an instance size under 16 bytes

We want valuetypes to be relatively small as they are copied around when they are passed to method calls, assigned, allocated in arrays, etc. If a valuetype has 4 Int32 fields it has an instance size of 128 bits and is just fine for use as a value type.  References are word sized, so 32 bits on a 32 bit machine, and 64 on a 64 bit machine.  There are also some padding for alignment issues, but this is a rough approximation, so don’t get too hung up on the exact size… we are just asking for a spirit of smallness… ;-)  The 16 byte number is a based on some understanding of how the machine works and some empirical testing but is mostly a “gut feelings” number.  Treat this as a rule of thumb, and like Rico would say, measure!



Value semantics are desirable

Someone else on the thread answered the question about Value semantics, but I thought it was right on, so here it is verbatim:  

A value object is an object for which identity is meaningless.  In other words, equality is based on its value, not its identity.  Numbers are obvious values which is built into the language. These objects should be immutable and if you want a value object with another value you get a new value object.