Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

In .net, the value types are stored on stack where as reference types are stored on managed heap. What is the reason for this one? Is it not possible to exchange their storage locations?

share|improve this question
4  
"the value types are stored on stack where as reference types are stored on managed heap." This is a huge fallacy - value types are equally able to be stored in the heap (via boxing or embedded in a reference type), or could be stored in a register. And what about references? (nether reference type nor value type) –  MattDavey Mar 29 '12 at 9:47
add comment

2 Answers

up vote 6 down vote accepted

The stack is an implementation detail. The important thing is the reference/value distinction.

Is it not possible to exchange their storage locations?

It's very easy to store value types on the heap.

class ReferenceInt
{
    public int Field;
}

ReferenceInt n = new ReferenceInt();
// n.Field is now stored on the heap.
share|improve this answer
    
@Dan.. in the above example n.Field is reference type right!! So it will store on heap, but in above statement you said that easy to store value types on heap... two types are storing in heap only. two solutions sounds like same... can you please explain. –  YSM Mar 29 '12 at 3:45
2  
No, n.Field is an int, which is a value type. –  dan04 Mar 29 '12 at 5:08
    
But the n.Field value type would be embedded in the ReferenceInt type, which is stored in the heap. So n.Field would not be on the stack. –  MattDavey Mar 29 '12 at 9:49
add comment

These brilliant articles by Eric Lippert should tell you what you need to know. To sum up: don't worry about it.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.