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?
Auto
says The runtime automatically chooses an appropriate layout for the members of an object in unmanaged memory. Objects defined with this enumeration member cannot be exposed outside of managed code. Attempting to do so generates an exception. Maybe this is used to enforce usage only in managed code. Reason for that might be that the layout changed several times in .NET history (just an assumption). More: msdn.microsoft.com/en-us/library/… – Carburetorauto
seems ok, maybe the question should be why so few other types use it. – PassoverDateTime*
pointer type in C#, withunsafe
context, for example this program works fine:unsafe { int[] memory = { 123, 456, 789, 333, 666, 999, }; fixed (int* pointer = &memory[0]) { var pointer2 = (DateTime*)pointer; Console.WriteLine(pointer2->DayOfWeek); pointer2 += 2; Console.WriteLine(pointer2->DayOfWeek); } }
. – Eisenberg