Value vs Reference Types

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
 
N

Nicholas Paldino [.NET/C# MVP]

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.
 
J

Jon Skeet [C# MVP]

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
 
W

Willy Denoyette [MVP]

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.
 
J

Jeff Louie

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<
 
W

Willy Denoyette [MVP]

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top