Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are Value Types created on the Stack and Reference Types created on the Heap?

Programming language books usually explain that value types are created on the stack, and reference types are created on the heap.

My question is Why.

like image 807
nehit Avatar asked Mar 28 '12 05:03

nehit


2 Answers

My question is Why.

Why do they "explain" that? Because sometimes the authors don't know any better themselves, and sometimes they're too lazy to explain it properly. The truth it rather more complicated.

Fortunately, Eric Lippert has written extensively around this:

  • The stack is an implementation detail, part 1
  • The stack is an implementation detail, part 2
  • The truth about value types

While I would usually try to at least include a paraphrase of the full answer here, I'm not going to do so here - because explaining it very briefly is almost bound to give a misleading result. Just go and read those blog posts - and then everything else Eric has written. It'll take weeks, but you'll be glad you did.

like image 118
Jon Skeet Avatar answered Nov 15 '22 10:11

Jon Skeet


Why does book authors writes like that ?

1.They have not read Eric Lippert enough.

2.They may not be stating about C# / Java compiler and they might be thinking of some other magic language.

3.They (authors) read the same from some other books (so it's in loop now)

4.[IMP] It's very easy to remember (not useful though) in 1 line statement rather than sayings of Eric Lippert.

5.Much of the programmers (like me) just reads, for them , in reality does not matter what happens in RAM. They want the out put shown on the screen (monitor). They want to remember these facts (whichever is easier and close to reality) for the purpose of interview.

6.Most of Interview takers in the current software industry are not like Eric Lippert. So even they dont know in reality. So remembering the false one will be helpful.

like image 23
Dhananjay Avatar answered Nov 15 '22 09:11

Dhananjay