CSharp examples for Custom Type:Operator Overloading
Implement add operation with method
using System;//from w w w .j a v a2 s. com 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 Add(TimeSpan timeSpan1, TimeSpan timeSpan2) { TimeSpan sumTimeSpan = new TimeSpan(); sumTimeSpan.Seconds = timeSpan1.Seconds + timeSpan2.Seconds; return sumTimeSpan; } } class TimeSpanTest { public static void Main() { TimeSpan totalTime; TimeSpan myTime = new TimeSpan(1,20,30); TimeSpan yourTime = new TimeSpan(2,40,45); totalTime = TimeSpan.Add(myTime, yourTime); Console.Write("My time: "); myTime.PrintHourMinSec(); Console.Write("Your time: "); yourTime.PrintHourMinSec(); Console.Write("Total time: "); totalTime.PrintHourMinSec(); } }