.NET DateTime Does Not Have a Predefined Size

2019-06-18 22:39发布

问题:

Since DateTime is a struct with members that appear to break down into simple mathematical values, I'm not sure why using sizeof() on it produces the message in the question title.

回答1:

Because the CLR can only determine the size at runtime... one of the reasons for this is "padding" (platform dependent)...

For all other types, including structs, the sizeof operator can be used only in unsafe code blocks. Although you can use the Marshal.SizeOf method, the value returned by this method is not always the same as the value returned by sizeof. Marshal.SizeOf returns the size after the type has been marshaled, whereas sizeof returns the size as it has been allocated by the common language runtime, including any padding.

Ref.

see also How do I check the number of bytes consumed by a structure?



回答2:

The full error text you get, is:

error CS0233: 'System.DateTime' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf)

So if you do use unsafe context (be sure to go to the C# project's "Properties", the "Build" tab, and set a check mark in "Allow unsafe code" to make the below compile) it works fine:

    static void Main()
    {
        int s;
        unsafe
        {
            s = sizeof(DateTime);
        }
        Console.WriteLine(s); // writes 8
    }

With the unsafe keyword, sizeof() will work with all enum types and with all struct types that do not have instance fields of reference type (and DateTime is a struct with no reference type members, for sure).

Without the unsafe keyword, you cannot use sizeof. (However, since C# 2 you are allowed to use it on pre-defined types like int and on enum types, but not on other structs like DateTime, as you saw.)


Note that the DateTime struct is exceptional in that Marshal.SizeOf<DateTime>() (or Marshal.SizeOf(typeof(DateTime)) prior to .NET version 4.5.1 (2013)) will throw an exception. This is because of the unusual (for a struct) structure layout "Auto".



回答3:

Alex Pinsker wrote nice solution for getting the size of DateTime (or any other type).