I have a small class, let’s call uomvalue, which contains a UOM and a Value field.
I have an implicit operator which converts a double to the Value field, when directly applied.
So if I use it the “normal” way, all is fine:
obj.UOM = "ft";
obj.Value = 123.4; //normal assignment
My problem is that when I assign using the implicit operator:
obj = 123.4; //impl op assignement
…the whole object is replaced, and any assignment I may have already made to the UOM is lost.
This may fall into the “dumb question” category because I really haven’t spent any time to figure this out, but is there a simple way to do this where I can keep the old value for the UOM when the impl. op. is used?
Simplest answer: don’t have an implicit conversion from
double. Implicit conversions like this are almost always a bad idea in my view. (There are exceptions, but it doesn’t sound like this is one of them.)It feels to me that implicit conversions are also more appropriate for immutable types, where the situation you’re describing simply can’t occur. It seems to me that your code would definitely be clearer without the implicit conversion. For example:
is now obvious in terms of what it’s doing.
And no, you can’t write an implicit operator which tries to preserve an existing value. After all, the conversion all happens before the assignment – nothing in the expression
123.4knows anything aboutobj… so you’d have to make the assignment operator itself know that it should use some part of value of the variable which is going to be assigned as part of working out the value to be assigned. That becomes problematic when there isn’t such a value beforehand.All of that’s getting way to complicated: ditch the conversion 🙂