How to make += operator keep the object reference?
- by orloffm
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?