Reference Types in Value Types

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi,
I'm creating a struct hat contains an array. Unfortunatly, all arrays are
reference types, which means that when someone copies/assigns it, they have a
reference to the orginal object, which defies the point of creating a struct!
And to top it off, my array contains reference objects!
If anyone has any ideas could they please tell me?

Reuben
 
Reuben said:
I'm creating a struct hat contains an array. Unfortunatly, all arrays are
reference types, which means that when someone copies/assigns it, they have a
reference to the orginal object, which defies the point of creating a struct!
And to top it off, my array contains reference objects!
If anyone has any ideas could they please tell me?

Well, what are you trying to achieve? A deep copy? I'd just provide a
method which creates a deep copy. You're unlikely to want to start
creating a deep copy *every* time the value is assigned though, I'd
have thought.
 
My problem is that when you assign a value type to a variable, modifications
on the original shouldn't affect the copy. However, because the both copies
contain the same reference to the same array, changes on one affect the
other, like you would expect from a reference type. I need a way to implement
this for the assignment operator (=) so that my type behaves in a manner
appropiate to value types.

I hope this clears that up.
Reuben.
 
Reuben said:
My problem is that when you assign a value type to a variable, modifications
on the original shouldn't affect the copy.

Well, that depends on the members. If they're reference type members,
I'd expect the modifications to affect the copy, because the copy is a
copy of the references.
However, because the both copies
contain the same reference to the same array, changes on one affect the
other, like you would expect from a reference type. I need a way to implement
this for the assignment operator (=) so that my type behaves in a manner
appropiate to value types.

You can't.

You might want to consider making your type immutable instead, so that
a new copy is created any time you want to make a change. You could
then make it a reference type instead. String is built this way, by the
way.
 
Back
Top