Articles → .NET → Operator Overloading In C#

Operator Overloading In C#






Scenario




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 <return_type> operator<operator_type>(<input_parameters>)




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


Picture showing the output of operator overloading in C#

Click to Enlarge


Benefits


  1. Simplified programming syntax
  2. 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;
  }
}



Posted By  -  Karan Gupta
 
Posted On  -  Wednesday, April 1, 2015

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250