What happens to a reference type in a valuetype struct?

D

DaTurk

I was just curious. I know that a struct is value type by definition,
and will be placed on the stack, but what if you have a reference type
in the struct, say a string, or an array. Where will that be placed?
 
D

Dustin Campbell

I was just curious. I know that a struct is value type by definition,
and will be placed on the stack, but what if you have a reference type
in the struct, say a string, or an array. Where will that be placed?

The reference type is actually allocated on the heap but the reference is
on the stack (in the value type) -- assuming that your value type is on the
stack.

Best Regards,
Dustin Campbell
Developer Express Inc.
 
B

Bruce Wood

DaTurk said:
I was just curious. I know that a struct is value type by definition,
and will be placed on the stack, but what if you have a reference type
in the struct, say a string, or an array. Where will that be placed?

The value type will be big enough to accommodate a reference (pointer)
to the reference type (plus anything else in the value type). The
storage for the state (fields) of the reference type itself will always
be on the heap.

By the way, this type of construct is possible, but it's usually best
that the reference type in question be immutable. If the state (fields,
contents) of the reference type can be changed then the value type will
act oddly, to say the least.

I do just what you described to implement a Measure: a quantity coupled
with a unit of measure (for example 5 combined with UnitOfMeasure.Feet
to represent five feet). The Measure is a struct, but the UnitOfMeasure
is a class. The important point is that the UnitOfMeasure class has no
properties that can be set, and its methods never change it: once it's
constructed it's immutable. This keeps the Measure struct acting in
reasonable ways.
 
J

Jon Skeet [C# MVP]

DaTurk said:
I was just curious. I know that a struct is value type by definition,
and will be placed on the stack

No, not necessarily. A value type is stored in the same context as it
is declared: if it's a member of a reference type, for instance, it
will be on the heap, as part of the data for the object.
but what if you have a reference type
in the struct, say a string, or an array. Where will that be placed?

The reference is placed in the same context as the rest of the data for
the struct. The object that the reference refers to will certainly be
on the heap.

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

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