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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
    public class Money
    {
        public double Value { get; private set; }

        public Money(double value)
        {
            Value= value;
        }

        public static implicit operator Money(double value)
        {
            return new Money { Value = value };
        }
    }

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:

1
2
3
4
5
6
7
8
9
    public static Money operator +(Money a, Money b) 
    { 
        return a.Value + b.Value;
    }

    public static Money operator -(Money a, Money b) 
    { 
        return a.Value - b.Value;
    }

We then can use these methods on our code like this:

1
2
3
4
    Money money = 100d;
    Money money2 = 50d;

    Money result = money + money2;
comments powered by Disqus