C# structs and the heap question

F

faustino Dina

Hi,

I have a question about how C# handles struct. From the help, struct
variables are stored in the stack while class objects are stored in the
heap. Then what happens when I add a struct value to a colection?

struct MyStruct
{
public int X;
}

MyStruct s;

ArrayList list = new ArrayList();
list.Add(s);

In C/C++ store stack addresses on a global collection can lead to hard to
trace problems. But how C# works? In this case what is stored on the list
collection: struct, a reference to the stack or s is cloned into the heap
and that reference is added to the collection?

Thanks in advance
 
J

Jon Skeet [C# MVP]

faustino Dina said:
I have a question about how C# handles struct. From the help, struct
variables are stored in the stack while class objects are stored in the
heap.

Unfortunately that's a rather simplistic approach.

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

(For instance, a value type which is part of a reference type will
always be on the heap.)
Then what happens when I add a struct value to a colection?

struct MyStruct
{
public int X;
}

MyStruct s;

ArrayList list = new ArrayList();
list.Add(s);

This is actually a third case - here you're *boxing* the struct value.
This basically creates a strongly-typed object on the heap, containing
your value. To get it back as a value type, you need to unbox the
reference, which you do using casting syntax:

s = (MyStruct) list[0];
In C/C++ store stack addresses on a global collection can lead to hard to
trace problems. But how C# works? In this case what is stored on the list
collection: struct, a reference to the stack or s is cloned into the heap
and that reference is added to the collection?

Essentially the latter.
 

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