Articles → CSHARP → Operator Overloading In C#
Operator Overloading In C#
Purpose
Scenario
public class WeekClass {
public enum WeekDays {
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
}
public WeekClass() {
CurrentDayOfWeek = WeekDays.Monday;
}
public WeekDays CurrentDayOfWeek {
get;
set;
}
}
Syntax
public static <return_type> operator<operator_type>(<input_parameters>)
Implementation
public static WeekClass operator++(WeekClass wc) {
switch (wc.CurrentDayOfWeek) {
case WeekDays.Monday:
wc.CurrentDayOfWeek = WeekDays.Tuesday;
break;
case WeekDays.Tuesday:
wc.CurrentDayOfWeek = WeekDays.Wednesday;
break;
case WeekDays.Wednesday:
wc.CurrentDayOfWeek = WeekDays.Thursday;
break;
case WeekDays.Thursday:
wc.CurrentDayOfWeek = WeekDays.Friday;
break;
case WeekDays.Friday:
wc.CurrentDayOfWeek = WeekDays.Saturday;
break;
case WeekDays.Saturday:
wc.CurrentDayOfWeek = WeekDays.Sunday;
break;
case WeekDays.Sunday:
wc.CurrentDayOfWeek = WeekDays.Monday;
break;
}
return wc;
}
How To Use
WeekClass wc = new WeekClass();
Console.WriteLine(wc.CurrentDayOfWeek);
wc++;
Console.WriteLine(wc.CurrentDayOfWeek);
Output
Click to Enlarge
Benefits
- Simplified programming syntax
- Abstraction.
Code
public class WeekClass {
public enum WeekDays {
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
}
public WeekClass() {
CurrentDayOfWeek = WeekDays.Monday;
}
public WeekDays CurrentDayOfWeek {
get;
set;
}
public static WeekClass operator++(WeekClass wc) {
switch (wc.CurrentDayOfWeek) {
case WeekDays.Monday:
wc.CurrentDayOfWeek = WeekDays.Tuesday;
break;
case WeekDays.Tuesday:
wc.CurrentDayOfWeek = WeekDays.Wednesday;
break;
case WeekDays.Wednesday:
wc.CurrentDayOfWeek = WeekDays.Thursday;
break;
case WeekDays.Thursday:
wc.CurrentDayOfWeek = WeekDays.Friday;
break;
case WeekDays.Friday:
wc.CurrentDayOfWeek = WeekDays.Saturday;
break;
case WeekDays.Saturday:
wc.CurrentDayOfWeek = WeekDays.Sunday;
break;
case WeekDays.Sunday:
wc.CurrentDayOfWeek = WeekDays.Monday;
break;
}
return wc;
}
}