Reputation: 351
I have class as following:
public class A
{
int i;
}
When I am creating and object of class as following:
A obj=new A();
I can understand the object is allocated in Heap. Now the class got a integer variable. Where the member variable "i" is allocated (in stack or heap)?
Upvotes: 0
Views: 88
Reputation: 1
All class member will go in heap with continues memory allocation. All variables in a method (local variables) are allocated on stack.
Upvotes: 0
Reputation: 1503280
Where the member variable "i" is allocated (in stack or heap)?
It's on the heap - it's part of the memory of the object. (If the variables didn't end up as part of the data of the object, what would you expect the object's data to consist of?)
Of course, as Eric Lippert would point out, the stack is an implementation detail (part one; [part two][2]
). Normally you shouldn't worry too much about it. In practice, there have been more and more cases where local variables have started being allocated on the heap:
I haven't seen much evidence of the reverse being true, although it might be possible for a future CLR to use escape analysis to prove that a particular object never had to be allocated on the heap, and allocate it on the stack instead. (I believe some JVMs do this.)
Upvotes: 1
Reputation: 1064004
i
is a field, so it is part of the instance itself. Since the instance is on the heap, and is composed of i
... thus i
is on the heap.
This becomes more interesting for struct
types, as the instance (the value) can be just about anywhere, thus i
can be just about anywhere. All you can say is "inside the instance".
Upvotes: 1