What is the proper way to implement assignment by value for a reference type? I want to perform an assignment, but not change the reference.
Here is what I’m talking about:
void Main()
{
A a1 = new A(1);
A a2 = new A(2);
a1 = a2; //WRONG: Changes reference
a1.ValueAssign(a2); //This works, but is it the best way?
}
class A
{
int i;
public A(int i)
{
this.i = i;
}
public void ValueAssign(A a)
{
this.i = a.i;
}
}
Is there some sort of convention I should be using for this? I feel like I’m not the first person that has encountered this. Thanks.
EDIT:
Wow. I think I need to tailor my question more toward the actual problem I’m facing. I’m getting a lot of answers that do not meet the requirement of not changing the reference. Cloning is not the issue here. The problem lies in ASSIGNING the clone.
I have many classes that depend on A – they all share a reference to the same object of class A. So, whenever one classes changes A, it’s reflected in the others, right? That’s all fine and well until one of the classes tries to do this:
myA = new A();
In reality I’m not doing new A() but I’m actually retrieving a serialized version of A off the hard drive. But anyways, doing this causes myA to receive a NEW REFERENCE. It no longer shares the same A as the rest of the classes that depend on A. This is the problem that I am trying to address. I want all classes that have the instance of A to be affected by the line of code above.
I hope this clarifies my question. Thank you.
I wish there was a “second best” answer option, because anyone who mentioned Observer deserves it. The observer pattern would work, however it is not necessary and in my opinion, is overkill.
If multiple objects need to maintain a reference to the same object (“MyClass”, below) and you need to perform an assignment to the referenced object (“MyClass”), the easiest way to handle it is to create a ValueAssign function as follows:
Observer would only be necessary if other action was required by the dependent objects at the time of assignment. If you wish to only maintain the reference, this method is adequate. This example here is the same as the example that I proposed in my question, but I feel that it better emphasizes my intent.
Thank you for all your answers. I seriously considered all of them.