C# Conversion Operator Overloading

C# Code Snippets Conversion Operator Overloading
Share:

About

In this code snippet, we will take a look at conversion operator overloading in C#. 

Conversion operators can be overloaded just like regular operators. This is useful when you want to be able to convert your custom object to another type. We have two types of conversions, implicit and explicit. Implicit conversion can be “just done” no special syntax is required. Meanwhile, explicit conversion requires casting.

Let’s look at the code example below to see how to overload conversion operators.

Code:

using System;

namespace conversionOperatorOverloading2
{
    class Program
    {
        static void Main(string[] args)
        {
            int num = 2;

            //Cast num of type int to type of MyNumberClass.
            MyNumberClass number = (MyNumberClass)num;
            //This can be done implicitly so there is really no need to do this: (MyNumberClass)
            MyNumberClass number2 = num;


            //Cast MyNumberClass to int. This must be done explicitly like so: (int)
            Console.WriteLine("Int value of number: " + (int)number);

            Console.ReadLine();
        }

        class MyNumberClass
        {
            public string Number { get; set; }

            public MyNumberClass(string number)
            {
                Number = number;
            }

            public static explicit operator int(MyNumberClass display)
            {
                //Here we perform the conversion from our custom type to an int.
                switch (display.Number)
                {
                    case "zero": return 0;
                    case "one": return 1;
                    case "two": return 2;
                    case "three": return 3;
                    //You get the idea...
                    default: return 0;
                }
            }

            public static implicit operator MyNumberClass(int num)
            {
                //Here we perform the conversion from int to our custom type.
                switch (num)
                {
                    case 0 : return new MyNumberClass("zero");
                    case 1: return new MyNumberClass("one");
                    case 2: return new MyNumberClass("two");
                    case 3: return new MyNumberClass("three");
                    //You get the idea...
                    default: return new MyNumberClass("zero");
                }
            }
        }
    }
}

Resulting output:

Share:

Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger