Home of the AlmostImplementedException

implicit/explicit conversion operator – How to convert a custom object to a simple type

Today I came across a C#-feature i know for a long time, but never used in real code. I think thats about to change. 😀

First, have a look at the following lines and try to figure out what happens:

How is it possible to add an object to a double? Normally it won’t even compile.
The answere is the implicit conversion operator.
Since there are two conversion operator, lets explain the difference first.
The implicit conversion operator converts a value without any doing of the user if it is required and is therefore easier to use. The explicit conversion operator requires a cast. This way the user has to specify which conversion should be used.
With CleanCode in mind the explicit conversion operator is the only choice, but there are other reasons why the implicit conversion operator is sometimes dangerous.

But before dig in deeper just have a look at our Distance-Class:

As you can see, there is a static implicit operator for the type double. This method converts a Distance-object to double if needed.
The explicit operator looks exactly the same. Just change implicit to explicit.
But after that the first example won’t work anymore. Now you’ll get a compile error. But thats easy to fix, just add a cast to the distance-variable ((double)distance) and the code works again.

Earlier I said that the implicit conversion is sometimes dangerous and the next example will show you why. We add a ToString-Method to our Distance-Object and a WriteLine to the Main-Method.

What will you see when you execute this program? If you say: “Money: 10.25 meter” you’re wrong!
The result is “10.25”. Since we have an implicit conversion and the WriteLine-Method has a version for double, the converter is called.
ok, thats inconvenient but not that dangerous. But what happens when we add another implicit converter, this time for int?

Will there be an error? No! But which value will you see? Its the int-value. Imagine this happens with a method call that actually do something with the value.
BTW, VisualStudio might show you the double-version of the method when you follow the call, because it can’t know which conversion is choosed at runtime.
Its very bad coding style when you don’t know which method is called and may lead to very strange problems.

Therefore its better to use the explicit convertion operator and let the user of your object explicit decide which convertion he wants to use.

Share :

One thought on “implicit/explicit conversion operator – How to convert a custom object to a simple type

Leave a Reply

Your email address will not be published. Required fields are marked *