It is said that value types are stored in stack. But what happens when we declare a value type with new?
For example
int a;
is stored in stack, but
int b=new int();
Where does b is stored? Heap or stack? It’s confuses me. It’s like a reference, but it’s a value type.
This is said frequently but it is obviously false. When you make an array with 100 ints, do those ints live on the stack, or the heap?
The idea that the lifetime of storage has something to do with the type of the storage is simply false. The correct statement is that variables of value type that are of known short lifetime can be allocated from short-term storage, which sounds pretty obvious when you put it that way.
Make sure you’re clear on that: it is simply false that
int i;means "allocate i on the stack". It means "allocate storage for i"; if that storage lifetime is known to be short then it can be allocated on the short term store. Otherwise it is allocated on the long-term store.You’re thinking that "new" causes new storage to be allocated off the heap. It does not. Think of "new" as meaning "obtain storage and then invoke a constructor".
The storage obtained for a class type is always on the heap because the lifetime of the class data is not known to be short. The storage obtained for a value type is documented as being on the stack, and then the value is copied to its final destination, which might be on the stack or the heap. However that allocation and copy can be copy-elided if the compiler can determine that it is safe to do so.
Here are some articles that will help:
http://blogs.msdn.com/b/ericlippert/archive/2010/09/30/the-truth-about-value-types.aspx
https://ericlippert.com/2010/10/11/debunking-another-myth-about-value-types/