Wednesday, July 30, 2014

Understanding Implicit and Explicit in Conversion Operators (C# reference)

In the below example it has duplicates for each of the type casting. So for understanding I included both but commented the code. If you want to give it a try please uncomment the operator with corresponding colored typecast method to statements in Main


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

namespace Apps
{
    class MyTime1
    {
        public int h { setget; }
        public int m { setget; }
        public int s { setget; }
        public MyTime1(int h, int m, int s)
        {
            this.h = h;
            this.m = m;
            this.s = s;
        }
        public MyTime1(int h)
        {
            this.h = h;
        }
        public int TotalSeconds
        {
            get
            {
                return h * 3600 + m * 60 + s;
            }
        }

        //public static implicit operator int(MyTime1 t1)
        //{
        //    return t1.TotalSeconds;
        //}

        //public static explicit operator int(MyTime1 t2)
        //{
        //    return t2.TotalSeconds;
        //}

        //public static implicit operator MyTime1(int n)
        //{
        //    return new MyTime1(n);
        //}

        public static explicit operator MyTime1(int n)
        {
            return new MyTime1(n);
        }
    }
    class UnderstandingImplicitAndExplicitOverloading
    {
        public static void Main()
        {
            MyTime1 t1 = new MyTime1(10, 59, 59); 

            //int sec1 = t1;       // convert from int to class object IMPLICITLY
            //Console.WriteLine(sec1);

            //int sec2 = (int)t1;   // convert from int to class object EXPLICITLY
            //Console.WriteLine(sec2);

            // Constructor Overloading takes place. other form MyTime t2 = new MyTime(60);
            //MyTime1 t2 = 10;         // convert from class object to int IMPLICITLY

            MyTime1 t2 = (MyTime1)10;         // convert from class object to int EXPLICITLY

            Console.WriteLine(t2.TotalSeconds);
            Console.WriteLine(t1.TotalSeconds);
        }
    }
}

No comments:

Post a Comment