TheSharperDev

Educating about C# and F#

Explaining Implicit Conversion Operators in C#

Sometime ago at work, I discovered a class that could automatically convert to and from a string whenever it was needed. At first I was confused as to how that could occur.Then I looked through the class definition and encountered the implicit operator.

It wasn’t something I was familiar with, so I thought it was worth blogging about to let you know it exists as well.

Types in C#

C# is a strongly typed language. The compiler enforces proper uses of types.

If you have a method that takes type A, and you attempt to pass type B to it, compile error!!!

There are implicit conversions available for certain builtin types, like the following:

Num is an int, but it can be passed to a method that accepts a double. This kind of implicit conversion isn’t super radical to me.

Outside of these builtin types, I can’t remember ever encountering any other implicit conversions.

It turns out to be really easy to define an implicit conversion between any type that you need.

Implicitness

Lets say we had defined a class to hold file paths for us.

I wouldn’t suggest doing this in real life, definitely better to use the C# defined Path class, but it’s an example.

The FilePath class has an internal _path string variable to hold the path for us. Pretty simple.

Lets define a PathOps class that has some methods useful for dealing with paths.

One method takes a string and the other takes a FilePath. Not that cleanest API, but lets see what happens when we leverage implicit conversion.

Lets add two implicit operators to our class.

These implicit operators will automatically convert between a string and a FilePath whenever is needed.

So when we now call these methods, it doesn’t matter whether we use a string or a FilePath.

Whatever type the method requires, C# will convert to that type because of the implicit operators.

Explanation

What’s the format for creating an implicit conversion? Quite simply the following:

«access specifier» static implicit operator «expected type» («current type» currentValue)

When C# has a FilePath but needs a string, it calls this method:

When it has a string but needs a FilePath, it calls the other method:

Pretty simple definition.

Warning

While this can be a useful feature, I would argue that being explicit is the better way to go in most circumstances.

Implicit conversions definitely have a cost to them. It could cause potentially subtle bugs or the wrong method to be called. I can’t personally think of a use case where implicit conversion saved me enough time to use it.

Just to let you know where I stand on this language feature.

Wrapping Up

Until recently, implicit conversion in C# wasn’t something I realized I had control over. It’s an interesting feature, but not something I plan on implementing soon.

References