DaTurk wrote:
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.