So, a couple of questions, actually:
int
(Int32
) is specified to be (obviously) 32 bits. What about an int?
(Nullable<int>
)? My gut tells me that it would be 32 bits for the integer plus 8 more bits for the boolean, but perhaps the implementation is more intricate than that.sizeof(int?)
; but as int?
is a managed type this is not allowed. I understand that the size of a type may be platform-dependent, and that in the case of objects which contain references to other objects, a sizeof
-like operation would be misleading. However, is there a way to get a "baseline" size (i.e., what the size of a newly instantiated instance would be) for a managed type, given the current environment?String is a reference type, a variable of type Int32 is a value type. Assigning a null value to a value type was a challenge for a long time until the concept of nullable types were introduced. You cannot assign a null value directly to a value type. You cannot assign a null value directly to a value type.
Nullable<int> i = null; A nullable type can represent the correct range of values for its underlying value type, plus an additional null value. For example, Nullable<int> can be assigned any value from -2147483648 to 2147483647, or a null value.
Nullable types were introduced with version 7.0 of C#. These types represent instances of the System. Nullable<T> class. They are the values of an underlying type T and an additional null value. The T can be any non-nullable value type, but it cannot be a reference type.
You typically use a nullable value type when you need to represent the undefined value of an underlying value type. For example, a Boolean, or bool , variable can only be either true or false . However, in some applications a variable value can be undefined or missing.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With