Value vs Reference Types

  • Thread starter Thread starter Manco
  • Start date Start date
M

Manco

Is it true that:

1. inside a method, value-type variables and reference-type variables are
all on the stack
2. the value-type variable is on the stack, but the reference points to a
memory address in the heap
 
Manco,

See inline.
1. inside a method, value-type variables and reference-type variables are
all on the stack

Yes. The value types are actually in the memory space on the stack, and
the references are just that, references to the managed objects, which do
not reside on the stack.
2. the value-type variable is on the stack, but the reference points to a
memory address in the heap

The managed heap, yes. I wouldn't say it points to a memory address
(because ultimately, it must), but rather, just an object on the heap. The
GC can move the location of that object around at will.

Hope this helps.
 
Manco said:
Is it true that:

1. inside a method, value-type variables and reference-type variables are
all on the stack

All local variable values are indeed on the stack - but the value of a
reference type variable is only a reference, not the object itself.
2. the value-type variable is on the stack, but the reference points to a
memory address in the heap

Yes, I think so - it depends on exactly what you mean.

See http://www.pobox.com/~skeet/csharp/memory.html
 
Manco said:
Is it true that:

1. inside a method, value-type variables and reference-type variables are
all on the stack Yes.
2. the value-type variable is on the stack, but the reference points to a
memory address in the heap
2a. Yes (see 1). But it holds the real value of the type (the bits).
2b. the reference-variable holds a reference to a memory location on the GC
heap.

Willy.
 
Manco... As always someone is going to say there is an exception. So in
Visual C+ 2005 there is the concept of a managed class or type that goes
on
the "stack." At least it acts that way so that when the object goes out
of
scope, Dispose is called. In reality the object still goes on the
managed heap.

Regards,
Jeff
Is it true that:

1. inside a method, value-type variables and reference-type variables
are
all on the stack
2. the value-type variable is on the stack, but the reference points to
a
memory address in the heap<
 
Jeff Louie said:
Manco... As always someone is going to say there is an exception. So in
Visual C+ 2005 there is the concept of a managed class or type that goes
on
the "stack." At least it acts that way so that when the object goes out
of
scope, Dispose is called. In reality the object still goes on the
managed heap.

So it's no exception ;-)

Willy.
 
Back
Top