If you have Nullable<int>
, does this live on the stack? How many bytes does it take up?
views:
89answers:
3It shouldn't matter is the correct answer to both of your questions.
But, to entertain you, an instance of Nullable<T>
that isn't an element of a collection, is not a field of a reference type, is not a local in an iterator block or a hoisted local in a lambda or an anonymous method is probably stored on the stack.
But again, it shouldn't matter. This is an implementation detail (meaning it might be one way for the Microsoft implementation of the CLR but it doesn't have to be, and it could be another way for the Mono implementation of the CLR).
Microsoft employee Eric Lippert doesn't like it when you refer to value types living on the stack, but yes, Nullable<>
is a value type.
They generally live on the stack, and simply have a boolean member indicating whether the value is null or not. Hence (excluding padding bytes due to alignment) a Nullable<int>
takes 5 bytes.
A Nullable<T>
is a struct (and therefore a value type), so the same rules of allocation location apply as to any other struct.
Eric Lippert recently posted this: The Truth About Value Types