Custom Explicit and Implicit Conversion Operators in .NET C#
The implicit and explicit conversion operators were introduced in the C# language almost two decades ago. Although not a problem, it's likely that many programmers have never encountered this feature. For this reason, I've prepared a didactic example to introduce this feature to those who don't know it yet.
Explicit Operators
The main objective of explicit operators is to provide greater safety when performing critical or potentially risky conversions, commonly called cast (or explicit conversion).
Before explaining how to customize them, I need to show an example for those who are not yet familiar with this topic:
int temperature = 255;
Console.WriteLine((byte)temperature);
// OUTPUT: 255
In this case, we are performing an explicit conversion of a variable from type int to byte.
If we changed this example and the value provided was 256, what would be the result? Try it.
Now that we're familiar with the cast, we can proceed with our implementation example. See the following code:
public class Temperature
{
public decimal Celsius { get; set; }
public static explicit operator decimal(Temperature temperature)
{
return temperature.Celsius;
}
}
In addition to the Celsius property, our Temperature class has the signature and implementation of an explicit conversion operator, which receives an instance of the Temperature class and returns the value of the Celsius property (of type decimal).
Observe the following code:
Temperature marsTemperature = new Temperature { Celsius = -63.0m };
decimal celsius = (decimal)marsTemperature; // Cast
Console.WriteLine($"Temperature: {celsius}ºC");
// OUTPUT: Temperature: -63.0ºC
We've just instructed the compiler on how to handle an explicit conversion from an instance of Temperature to the decimal type. It's a useful feature.
Now, let's move on to implicit operators.
Implicit Operators
The objective of implicit conversion operators is basically to improve code readability. Thus, your code can be less verbose and more transparent, allowing type conversions to be performed more safely.
See the following example:
public class Temperature
{
public decimal Celsius { get; set; }
public static implicit operator Temperature(decimal value)
{
return new Temperature { Celsius = value };
}
public override string ToString()
{
return $"Temperature: {Celsius}ºC";
}
}
Again, in addition to the Celsius property, our Temperature class has the signature and implementation of an implicit conversion operator, which receives a value of type decimal and returns an instance of the Temperature class.
As we can observe, we're also overriding the ToString method, just to make our output more elegant.
In the following code example, we create a variable of type Temperature, which will be instantiated with the decimal value that represents the average temperature of planet Earth:
Temperature earthTemperature = 14.5m;
Console.WriteLine(earthTemperature);
// OUTPUT: Temperature: 14.5ºC
As we could observe in this example, implicit conversion operators are an excellent tool for simplifying code and improving readability, but should be used with caution to avoid unwanted conversions and data loss.
In this article, we saw the explicit and implicit conversion operators in C# and how they can be used to make code safer and more readable.
If you have any questions or suggestions, feel free to leave a comment. I'll be happy to try to help!
Follow me for more content like this.
Thanks for reading.