Using implicit conversion operators in C# to improve readability


Using implicit conversion operators in C# to improve readability

The implicit conversion operator is one of the coolest hidden features, in my opinion. I believe that the reason why it is not such a well-known function is that it is hard to figure out what to call it. I hear a lot of people calling it an implicit constructor, and I can truly understand where this comes from. But in any case, let’s use what Microsoft decided to call them.

Usage

The implicit conversion operator allows us to seamlessly convert one type into another. It’s easier to demonstrate through an example. Take a look at the following code:

We have a class called Color, which simply takes a hex code in its constructor. We also have our operator defined, but ignore that for now, it will become crystal clear soon. Then we have a Wall class, with a Paint method that receives a color. Simple enough, right?

Now let’s analyze our Main method in the Program.cs class. As you can see, we are creating an instance of the Wall class, and calling the Paint method. However, we are passing a string, not an instance of Color, how is that possible? Well, that’s due to the magic of our operator. If you analyze the operator at our Color.cs class, you can see that it calls the constructor, using the provided hex code.

This is a very simple scenario, but its potential is huge. For example. you can use it for social security numbers, coordinates, URIs, IP addresses, and much more. Just be sure to not go too crazy on it and have ultra-complex operators.

As another example, you can take a look at this AddressRange class, from an open-source C# emulator which I forked. Its operator can be seen in action in this Bootstrapper class. With it, I can cleanly specify either a single or multiple addresses, avoiding a massive amount of explicit instantiations. If you are curious about the project, more explanation can be found here and here.