CSharp examples for Custom Type:Operator Overloading
Implement add operation with operator overload
using System;/* w w w . ja v a 2 s .c o m*/ class TimeSpan { private uint totalSeconds; private const uint SecondsInHour = 3600; private const uint SecondsInMinute = 60; public TimeSpan() { totalSeconds = 0; } public TimeSpan(uint initialHours, uint initialMinutes, uint initialSeconds) { totalSeconds = initialHours * SecondsInHour + initialMinutes * SecondsInMinute + initialSeconds; } public uint Seconds { get { return totalSeconds; } set { totalSeconds = value; } } public void PrintHourMinSec() { uint hours; uint minutes; uint seconds; hours = totalSeconds / SecondsInHour; minutes = (totalSeconds % SecondsInHour) / SecondsInMinute; seconds = (totalSeconds % SecondsInHour) % SecondsInMinute; Console.WriteLine("{0} Hours {1} Minutes {2} Seconds", hours, minutes, seconds); } public static TimeSpan operator+ (TimeSpan timeSpan1, TimeSpan timeSpan2) { TimeSpan sumTimeSpan = new TimeSpan(); sumTimeSpan.Seconds = timeSpan1.Seconds + timeSpan2.Seconds; return sumTimeSpan; } public static TimeSpan operator++ (TimeSpan timeSpan1) { TimeSpan timeSpanIncremented = new TimeSpan(); timeSpanIncremented.Seconds = timeSpan1.Seconds + 1; return timeSpanIncremented; } public static bool operator> (TimeSpan timeSpan1, TimeSpan timeSpan2) { return (timeSpan1.Seconds > timeSpan2.Seconds); } public static bool operator< (TimeSpan timeSpan1, TimeSpan timeSpan2) { return (timeSpan1.Seconds < timeSpan2.Seconds); } public static bool operator== (TimeSpan timeSpan1, TimeSpan timeSpan2) { return (timeSpan1.Seconds == timeSpan2.Seconds); } public static bool operator!= (TimeSpan timeSpan1, TimeSpan timeSpan2) { return (timeSpan1.Seconds != timeSpan2.Seconds); } } class TimeSpanTest { public static void Main() { TimeSpan someTime; TimeSpan totalTime = new TimeSpan(); TimeSpan myTime = new TimeSpan(2,40,45); TimeSpan yourTime = new TimeSpan(1,20,30); totalTime += yourTime; totalTime += myTime; Console.Write("Your time: "); yourTime.PrintHourMinSec(); Console.Write("My time: "); myTime.PrintHourMinSec(); Console.Write("Total race time: "); totalTime.PrintHourMinSec(); if (myTime > yourTime) Console.WriteLine("\nI spent more time than you did"); else Console.WriteLine("\nYou spent more time than I did"); myTime++; ++myTime; Console.Write("\nMy time after two increments: "); myTime.PrintHourMinSec(); someTime = new TimeSpan(1,20,30); if (yourTime == someTime) Console.WriteLine("\nSpan of someTime is equal to span of yourTime"); else Console.WriteLine("\nSpan of someTime is NOT equal to span of yourTime"); } }