Structs and Ref types

B

Brette.Net

Hey All,

This may be a simple one but I thought I would throw it out there
because I can't find an answer. Structures are value types as we know.
Thus they are stored on the stack. What happenes though, if you have a
struct that contains a ref type such as a string? Is the struct still
a value type? Or is it now stored in heap space?

Brette.Net
 
K

Kevin Spencer

The struct instance is stored in the stack. The reference type instance is
stored in the heap. The struct only contains a reference to the actual
instance.

--
HTH,

Kevin Spencer
Microsoft MVP

Printing Components, Email Components,
FTP Client Classes, Enhanced Data Controls, much more.
DSI PrintManager, Miradyne Component Libraries:
http://www.miradyne.net
 
J

Jon Skeet [C# MVP]

This may be a simple one but I thought I would throw it out there
because I can't find an answer. Structures are value types as we know.
Thus they are stored on the stack.

No - that's a myth. The struct will be stored on the stack *if* it's a
local variable, or an instance variable of another value on the stack.
If it's an instance variable of a class, the value will be on the
heap.
What happenes though, if you have a
struct that contains a ref type such as a string? Is the struct still
a value type? Or is it now stored in heap space?

The struct is still a value type, and it contains a reference.

See http://pobox.com/~skeet/csharp/memory.html

Jon
 
B

Brette.Net

No - that's a myth. The struct will be stored on the stack *if* it's a
local variable, or an instance variable of another value on the stack.
If it's an instance variable of a class, the value will be on the
heap.


The struct is still a value type, and it contains a reference.

Seehttp://pobox.com/~skeet/csharp/memory.html

Jon

Great that makes sense!

Brette.Net
 

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