6

Possible Duplicate:
Fields of class, are they stored in the stack or heap?

If I have

Class A
{
    int k=0;
}

and I'm doing:

A x  = new A();

where is k stored? On the heap or the stack? And why?

Community
  • 1
  • 1
Royi Namir
  • 144,742
  • 138
  • 468
  • 792
  • 2
    Didn't you get the memo? [The stack is an implementation detail](http://blogs.msdn.com/b/ericlippert/archive/2009/04/27/the-stack-is-an-implementation-detail.aspx)! –  Jul 25 '11 at 21:09

3 Answers3

6

Even though k is an int which is a value type it is contained in a reference type, so it will be stored on the heap as part of the memory allocated for x - while this is an implementation detail, this is the current behavior of .NET.

BrokenGlass
  • 158,293
  • 28
  • 286
  • 335
  • That's an implementation detail that you should not rely upon. – Darin Dimitrov Jul 25 '11 at 21:06
  • 1
    @Darin: Yes, but the fact remains that this is the current answer to the actual question asked. Eric is right - the underlying implementation isn't the most important detail - but programmers should *understand* the likely underlying implementation for any feature they use and what the implications of it might be, if they want to write good code. I'm not suggesting we should rely on implementation details to get miniscule performance gains, but that if we just blindly assume the compiler/CLR will magically make any code fast, we'll write lots of crap code. – Jason Williams Jul 25 '11 at 21:17
4

There's no definite answer. The CLR does not define whether to put objects on the stack or heap.

For more info, read Eric Lippert's blog posts

Mark H
  • 13,797
  • 4
  • 31
  • 45
4

It's (probably - see below) stored on the heap, along with all the rest of the class's data.

It's not stored on the stack because it doesn't really make any sense to put it there. Since the value is part of a reference type, it continues to live even after the current procedure exits. If it were on the stack, though, then it would be deleted after stack frame is popped. This would render the object invalid, unless there were some truly monumental extra work going on to try and shuffle it up and down the stack in order to keep it alive.

Furthermore, stack is a small space and sticking every instance of every value type ever created in the code would result in it running out of space very, very quickly.

However, the most correct answer is that the location where data is stored is an implementation detail, so you should assume you don't (and can't) know. The real distinction between reference and value types is the on that's built into their names: For value types, operations such as assignment and passing as arguments results in the object's value being copied. For reference types, such operations create an additional reference to the original object.

Sean U
  • 6,730
  • 1
  • 24
  • 43