How are small data types packed in C#
.net, c#, memory-management, mono
Solution
This depends on the runtime, not the compiler. You can override the default behavior with `[StructLayout]`, which can help - though the default behavior should be fine.
That being said, if minimzing total size is an absolute requirement, you may want to consider a `struct` instead of a `class`. When using a class, each instance of the class is going to add significant overhead. Between the syncblk, TypeHandle, etc, as well as the reference (which on a 64bit system is another 8 bytes) object instance uses a fair amount of "extra" memory above and beyond your two shorts. For details, see "How the CLR Creates Runtime Objects".
Storing your data packed into a collection of value types can avoid this entirely, and keep the instances down to 8 bytes each total (plus the collection overhead). Of couse, this changes the semantics in terms of usage, but if you're only using two shorts, this will reduce the amount of overhead involved in your type, especially on 64bit systems.
Problem
I am not looking to improve performance or memory usage, this question was purely sparked from curiosity. Main Question Given the following class will the C# compiler (Mono + .NET) pack the two `short` variables into 4 bytes or will they consume 8 bytes (with alignment)? ``` public class SomeClass { short a; short b; } ``` Secondary Question If the answer to the above question was not 4 bytes, would the following alternative offer any advantages (where `SomeClass` is used in very large quantities): ``` // Warning, my bit math might not be entirely accurate! public class SomeClass { private int _ab; public short a { get { return _ab & 0x00ff; } set { _ab |= value & 0x00ff; } public short b { get { return _ab >> 8; } set { _ab |= value << 8; } } } ```