Author avatar

Dániel Szabó

Converting Your Own Way

Dániel Szabó

  • Sep 16, 2019
  • 5 Min read
  • 13 Views
  • Sep 16, 2019
  • 5 Min read
  • 13 Views
Languages Frameworks and Tools
C#

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:

1
2
3
float pi = 3.14f;
double dpi = pi;
Console.WriteLine($"pi: {pi},\ndpi: {dpi}");
csharp

Note how the value of the pi changes.

1
2
pi: 3.14,
dpi: 3.14000010490417
bash

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:

1
2
3
double pi = 3.14;
float fpi = (float)pi;
Console.WriteLine($"pi: {pi},\nfpi: {fpi}");
csharp

Note how the length of the numbers did not change.

1
2
pi: 3.14,
fpi: 3.14
bash

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:

1
2
3
static public implicit operator <class>(<type> value) {
	return new <class>() { <value> = value, <boolean> = false };
}
csharp

The function responsible for the explicit conversion looks like this:

1
2
3
static public explicit operator <type>(<class> <instance>){
	return <instance>.<value>;
}
csharp

Let's define our custom class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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();
        }
    }
}
csharp

Calling the code shows us how the conversion goes from one type to another.

1
2
3
From int: 3,
to: UserDefined.Conversions+CustomType,
With value: 3
bash

By adding this little code we can easily backward convert.

1
2
int bNumber = (int)magic;
Console.WriteLine($"From: {magical},\nWith value: {magical.Number},\nto: {bNumber}");
csharp

This results in the following output.

1
2
3
From: UserDefined.Conversions+CustomType,
With value: 3,
to: 3
bash

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.

0