The struct System.DateTime
and its cousin System.DateTimeOffset
have their structure layout kinds set to "Auto". This can be seen with:
typeof(DateTime).IsAutoLayout /* true */
or:
typeof(DateTime).StructLayoutAttribute.Value /* Auto */
or it can be seen from the IL which declares:
.class public auto ansi serializable sealed beforefieldinit System.DateTime
¯¯¯¯
Normally a struct (that is a .NET value type which is not an enum) written with C# will have layout "Sequential" (unless a StructLayoutAttribute
has been applied to specify another layout).
I searched through some common BCL assemblies, and DateTime
and DateTimeOffset
were the only publicly visible structs I found with this layout.
Does anyone know why DateTime
has this unusual struct layout?
This is going to require speculation, this decision was made a long time ago, well before .NET 1.0 shipped. The attribute on System.DateTime is at best a micro-optimization, not uncommon in .NET code. It is somewhat appropriate, the struct has only one field so there's never any issue with layout. The ones for the internal CustomAttribute structs were probably done by the same programmer. Doesn't matter either, unmanaged code never sees them.
The one for System.DateTimeOffset was done much later and almost certainly a copy-paste bug.
That programmer got away with it, no reason for the CLR to re-arrange the layout from the sequential version. Re-arranging with auto-layout occurs when the struct contains padding between fields that is large enough to fit another small field. Not the case for DateTimeOffet.
Some odds you'll get a Microsoft guru to pay attention to this when you file a feedback report for DateTimeOffset. It is wrong afaik. Post it to connect.microsoft.com