Say, I have a class:
class M
{
public int val;
And also a + operator inside it:
public static M operator +(M a, M b)
{
M c = new M();
c.val = a.val + b.val;
return c;
}
}
And I’ve got a List of the objects of the class:
List<M> ms = new List();
M obj = new M();
obj.val = 5;
ms.Add(obj);
Some other object:
M addie = new M();
addie.val = 3;
I can do this:
ms[0] += addie;
and it surely works as I expect – the value in the list is changed. But if I want to do
M fromList = ms[0];
fromList += addie;
it doesn’t change the value in ms for obvious reasons.
But intuitively I expect ms[0] to also change after that. Really, I pick the object from the list and then I increase it’s value with some other object. So, since I held a reference to ms[0] in fromList before addition, I want still to hold it in fromList after performing it.
Are there any ways to achieve that?
You shouldn’t expect
ms[0]to change. After it’s been initialized ,fromListisn’t connected withmsat all –fromListandms[0]happen to have the same value, but that’s all. += is returning a new value (as indeed it should) so you’re just changing the value stored infromList, which is completely independent of the value in the list. (Note that the values here are references, not objects.)Don’t try to change this behaviour – it’s doing the right thing. Change your expectations instead.
If you really want the contents of the list to reflect the change, you either need to change the value in the list to refer to the new object, or you need to change your code to mutate the existing object instead of creating a new one. If you take the latter approach you should not do this within an operator. Instead, create an
Addmethod, so you’d call:It’s fairly clear that that’s a mutating operation, so it won’t break any expectations.
Personally I’d try to use immutable types instead, and adjust your design so that you don’t need the list to change (or you operate on the list directly).