Unlike C++, in C# you can't overload the assignment operator.
I'm doing a custom Number class for arithmetic operations with very large numbers and I want it to have the look-and-feel of the built-in numerical types like int, decimal, etc. I've overloaded the arithmetic operators, but the assignment remains...
Here's an example:
Number a = new Number(55);
Number b = a; //I want to copy the value, not the reference
Is there a workaround for that issue?
You won't be able to work around it having the C++ look, since a = b; has other semantics in C++ than in C#. In C#, a = b; makes a point to the same object like b. In C++, a = b changes the content of a. Both has their ups and downs. It's like you do
In C++ (it will lose the reference to the first object, and create a memory leak. But let's ignore that here). You cannot overload the assign operator in C++ for that either.
The workaround is easy:
Disclaimer: I'm not a C# developer
You could create a write-only-property like this. then do a.Self = b; above.
Now, this is not good. Since it violates the principle-of-least-surprise (POLS). One wouldn't expect a to change if one does a.Self = b;
you can use the 'implicit' keyword to create an overload for the assignment:
Suppose you have a type like Foo, that you feel is implicitly convertable from a string. You would write the following static method in your Foo class:
Having done that, you can then use the following in your code:
Here is a solution that worked for myself :
Somewhere else in the code :
Maybe what you're looking for can be solved using C# accessors.
http://msdn.microsoft.com/en-us/library/aa287786(v=vs.71).aspx
It's still not at all clear to me that you really need this. Either:
or:
Instead of making a copy of the data when passing the reference you could make the class immutable. When the class is immutable having multiple references to it isn't a problem since it can't be changed.
Operations that changes the data would of course return new instances.