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

后端 未结 7 1793
悲哀的现实
悲哀的现实 2020-12-13 02:43

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 h

7条回答
  •  天命终不由人
    2020-12-13 03:17

    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";
    

提交回复
热议问题