What is the size of a Nullable<Int32>?

穿精又带淫゛_ 提交于 2019-12-05 01:02:42

You can take a look in ildasm or Reflector.

If has two fields: a bool and a T, so probably 8 bytes (assuming 4 byte alignment).

It is rather important to never ask a question like this because you won't get a straight answer.

But since you did anyway: the minimum size is 0 bytes. Which you'll get when the JIT optimizer manages to keep the value in a CPU register. The next size is 2 bytes, for bool? and byte?, 1 byte for HasValue, another byte for the value. Which you'll rarely get because local variables must be aligned to an address that's a multiple of 4. The extra 2 bytes of padding simply will never be used.

The next size is 3 for short? and char?, you'll now get 1 byte of padding.

Big leap to the next one, int? requires 5 bytes but the padding increases that to 8.

Etcetera. You find this out by writing a bit of code like this:

        int front = 42;
        bool? center = null;
        int back = 43;
        Console.WriteLine("", front, center, back);

And looking at the machine code instructions with the debugger. Note the ebp register offsets. And beware that the stack grows down.

I found a treatment on exactly this question here, which includes code for a simple console application to test the memory usage.

Basically,

…This indicates that the nullable type wrapper requires 4 bytes of storage…

Consider Marshal.SizeOf method. It allows to obtain size of managed value types. It is strange, but looks like size of nullable type equals to size of their type parameter (size of int? equals to size of int, etc.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!