Is there a workaround for overloading the assignment operator in C#?

Boyan Nikolov picture Boyan Nikolov · Nov 15, 2008 · Viewed 25k times · Source

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?

Answer

Reinhard Brongers picture Reinhard Brongers · Feb 5, 2009

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:

public static implicit operator Foo(string normalString)
{
    //write your code here to go from string to Foo and return the new Foo.
}

Having done that, you can then use the following in your code:

Foo x = "whatever";