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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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.