The implicit operator in C# and when it can be useful
A cool feature of C# that I lately used is the implicit operator
keywords and with them we can define the way for converting one type into another one implicitly. A good scenario when you can use that is presented in this example.
We define a class Money which will hold a double value for the amount of money.
We can now write the following line in our code, when we want to create a new Money object by assigning to it an amount of type double: Money money = 100d;
.
The compiler accepts this implicit conversion of double to Money without an error. If we have not defined the implicit operator then we would get this error: Error CS0029 Cannot implicitly convert type 'double' to 'XXX.Money'
.
More fun with operators
The example with the Money class gets more interesting if we think about adding or subtracting two amounts. Again we can define how the + and - operators should behave in that case by using the operator
keyword. We add the following two methods in the Money class:
We then can use these methods on our code like this: