Wednesday, July 30, 2014

Understanding Operator Overloading for ==, !=, <, >, ++


Program: UnderstandingOperatorOverloading.cs

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

namespace Apps
{
    class MyTime
    {
        public int h { setget; }
        public int m { setget; }
        public int s { setget; }
        public MyTime(int h, int m, int s)
        {
            this.h = h;
            this.m = m;
            this.s = s;
        }
        public int TotalSeconds
        {
            get
            {
                return h * 3600 + m * 60 + s;
            }
            set
            {
                TotalSeconds = value;
            }
        }
        // Operators == and != are logical pairs and one without other gives our error. So both should be overloaded.
        public static bool operator ==(MyTime t1, MyTime t2)
        {
            return t1.TotalSeconds == t2.TotalSeconds;
        }
        public static bool operator !=(MyTime t3, MyTime t4)
        {
            return t3.TotalSeconds != t4.TotalSeconds;
        }
        // Operators < and > are logical pairs and one without other gives our error. So both should be overloaded.

        public static bool operator >(MyTime t3, MyTime t4)
        {
            return t3.TotalSeconds > t4.TotalSeconds;
        }
        public static bool operator <(MyTime t3, MyTime t4)
        {
            return t3.TotalSeconds < t4.TotalSeconds;
        }
        // Overloading ++ operator
        public static MyTime operator ++(MyTime t1)
        {
            t1.s++;
            if (t1.s > 59)
            {
                t1.s = 0;
                t1.m++;
            }
            if (t1.m > 59)
            {
                t1.m = 0;
                t1.h++;
            }
            if (t1.h > 23)
            {
                t1.h = 0;
                t1.s++;
            }
            return t1;
        } 
    }
    class UnderstandingOperatorOverloading
    {
        public static void Main()
        {
            MyTime t1 = new MyTime(10, 59, 59);
            MyTime t2 = new MyTime(10, 20, 30);
            Console.WriteLine(t1 == t2);
            Console.WriteLine(t1 > t2);
            Console.WriteLine(t1 < t2);
            t1++; // Incrementing the class object - So ++ operator Overloading is used.            
            Console.WriteLine("{0}:{1}:{2}", t1.h, t1.m, t1.s);
        }
    }
}

No comments:

Post a Comment