Converting Your Own Way
This guide will show you how and when to use implicit conversions, explicit conversions, and user-defined conversions.
Sep 16, 2019 • 5 Minute Read
Introduction
Conversions in C# are everyday operations for most developers. We use it to verify inputs and solidify the flow of our applications. There are built-in conversions and supporting facilities in C# that allow you to maintain flexibility and consistency throughout your applications. By default, there are two main types of conversions: one is called implicit and the other is called explicit. C# also provides a way for you to define your own conversions, which are called user-defined conversions. By adhering to some rules, you are able to create your custom conversions that tell the compiler and the runtime how they should handle conversion between classes that you have created. First, we’ll take a look at implicit and explicit conversions and then turn our eyes toward the custom user-defined conversions.
Implicit Conversion
We call a conversion implicit when the change is done without needing to use the conversion operators.
For example:
float pi = 3.14f;
double dpi = pi;
Console.WriteLine($"pi: {pi},\ndpi: {dpi}");
Note how the value of the pi changes.
pi: 3.14,
dpi: 3.14000010490417
The \n character is a new-line character, which adds only that to the output, so we can see separate lines on our screen.
Explicit Conversion
We call a conversion explicit when the change is done with the use of a conversion operator.
For example:
double pi = 3.14;
float fpi = (float)pi;
Console.WriteLine($"pi: {pi},\nfpi: {fpi}");
Note how the length of the numbers did not change.
pi: 3.14,
fpi: 3.14
This is due to the fact that float and double use different resolutions or memory space to store their values. Simply put, they have different sizes. Conversion from double to float will result in the loss of information which you need to be aware of.
User-defined Conversions
In order to implement custom conversion or cast, we need to be aware that there are two functions that allow us to do this and need to be implemented in our class if we want this to work. A user-defined conversion consists of an optional explicit conversion followed by either an implicit or explicit user-defined conversion operator, finalized by an optional standard explicit conversion. If you are interested, check out this awesome guide on MSDN which explains everything, in detail, about user-defined conversions and their steps.
The function responsible for the implicit conversion looks like this:
static public implicit operator <class>(<type> value) {
return new <class>() { <value> = value, <boolean> = false };
}
The function responsible for the explicit conversion looks like this:
static public explicit operator <type>(<class> <instance>){
return <instance>.<value>;
}
Let's define our custom class.
using System;
namespace UserDefined
{
public class Conversions
{
public class CustomType {
public int Number { get; set; }
public bool magic { get; set; }
static public implicit operator CustomType(int value) {
return new CustomType() { Number = value, magic = false };
}
static public explicit operator int(CustomType magic)
{
return magic.Number;
}
}
static void Main(String[] args)
{
int aNumber = 3;
CustomType magic = aNumber;
Console.WriteLine($"From int: {aNumber},\nto: {magic},\nWith value: {magic.Number}");
Console.Read();
}
}
}
Calling the code shows us how the conversion goes from one type to another.
From int: 3,
to: UserDefined.Conversions+CustomType,
With value: 3
By adding this little code we can easily backward convert.
int bNumber = (int)magic;
Console.WriteLine($"From: {magical},\nWith value: {magical.Number},\nto: {bNumber}");
This results in the following output.
From: UserDefined.Conversions+CustomType,
With value: 3,
to: 3
As you can see, these two functions are all that is needed to convert between types, however, this is a fairly simple example and it can be further improved upon. The overall conversion is defined by your app requirements and what you need to implement in those two functions.
Conclusion
Starting from implicit conversions, throughout explicit conversions we build up our guide towards the user-defined conversions. These are widely used conversions in legacy corporate applications that support infrastructure or business logic. Basically, with two simple functions, you are able to create your custom class for conversion and C# allows you to define your own business logic to implement that. I hope you have found what you were looking for and it was worth your while. Thanks for reading.