implict – explicit type casting

Using operator overloading, we can also perform impliclit/explicit type casting. For example, in the following program, we are going to type cast Currency class object into dollars and cents, and from dollars and cents to Currency.

REMEMBER: When converting from user defined type to primitive type, we use “implicit” overloading and conversion, whereas when converting from primitive type to user defined type, we use “explicit” overloading.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication8
{
    struct Currency
    {
        public uint Dollars;
        public ushort Cents;

        public Currency(uint dollars, ushort cents)
        {
            this.Dollars = dollars;
            this.Cents = cents;
        }

        public override string ToString()
        {
            return string.Format("{0}.{1,-2:00}", Dollars, Cents);
        }

        public static implicit operator float(Currency value)
        {
            return value.Dollars + (value.Cents / 100.0f);
        }

        public static explicit operator Currency(float value)
        {
            uint dollars = (uint)value;
            ushort cents = (ushort)((value - dollars) * 100);
            return new Currency(dollars, cents);
        }
    }
      
    class Program
    {     

        static void Main(string[] args)
        {

            try
            {
                Currency balance = new Currency(50, 35);

                Console.WriteLine(balance);
                Console.WriteLine("balance is " + balance);
                Console.WriteLine("balance is (using ToString()) " + balance.ToString());

                float balance2 = balance;
                Console.WriteLine("After converting to float, = " + balance2);

                balance = (Currency)balance2;

                Console.WriteLine("After converting back to Currency, = " + balance);
                Console.WriteLine("Attempt to convert to out of range value");
                checked
                {
                    balance = (Currency)(-50.50);
                    Console.WriteLine("Result is " + balance.ToString());
                }

            }
            catch (Exception e)
            {
                Console.WriteLine("Exception occurred: " + e.Message);
                
             }



        }
    }
}

 

Tags:,

Add a Comment

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