tags:

views:

89

answers:

3

If you have Nullable<int>, does this live on the stack? How many bytes does it take up?

+3  A: 

It 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).

Jason
you are right. Not too important, just trying to understand exactly what is going on. If Nullable<int> takes up 2 memory frames and int takes up 1 then i would assume 1 is more efficient, am i wrong?
wcpro
If you're considering using a Nullable<int> then I'm guessing you might care about the null-ness of that int, so you'd probably be having some other piece of memory taken up with a different indicator if you don't use a Nullable<>?
Giraffe
@wcpro: You should choose `Nullable<int>` if it has the right meaning for whatever you are trying to model.
Jason
@downvoter: Explain.
Jason
+3  A: 

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.

Mania
so, really this takes up 8 bytes (with padding), am i wrong? Is nullable int way less efficient than int32?
wcpro
In practice yes, 8 bytes. On the stack this isn't a problem - allocating variables on the stack takes no time, and space should never be an issue (if it is, you have bigger problems). Array's though it can add up - if this is a concern for you you could always make a generic class which wraps an array of T along with a BitArray class indicating the non-null values, along with an index function which returns Nullable of T.
Mania
+1  A: 

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

SO: What is the size of a Nullable<Int32>?

Mitch Wheat