Oude artikelen van mijzelf: Overriding Operators

C

Wederom een ouder artikel terug gevonden, en volgens de google stats wordt deze nog vaak opgevraagd. Dus vandaar…

C# allows you to override any operator (=, +, -, etc) but why, what can you do with it…

Overriding Operators

You are probably wondering “why do you want to override an operator??“, well there are some situations where this can be very useful. For instance, in you application you are using a salary object which contains an employee’s basic salary and a bonus. The object you will create will look something like this:

   1:  public class salary
   2:  {
   3:          //normally you would create private variables and properties,
   4:          //but for this example I'll keep it very basic...
   5:          public double basicSalary;
   6:          public double bonus;
   7:  }

Every employee in a company will have a object like this, containing his (or hers) salary information. But what to do if you want to calculate totals. Well, you can create a method that loops trough all the employees and adds the basicsalary to a custom double and add the bonus to a custom double.

In some situations it can be more efficient to create an instance of the salary object and add the employee’s salary object to it:

   1:      salary TotalSalary = new salary();
   2:      foreach (employee emp in employees)
   3:          TotalSalary += emp.salary;

This can be achieved by overriding the ‘+’ operator. The code to do this is located within the salary object. The .Net framework ‘knows’ that it should use the custom operator instead of the default.

   1:          public static salary operator + (salary x, salary y)
   2:          {
   3:              salary retVal = new salary();
   4:              retVal.basicSalary = x.basicSalary + y.basicSalary;
   5:              retVal.bonus = x.bonus + y.bonus;
   6:
   7:              return retVal;
   8:          }

The operator keyword tells the compiler that it is an override for a operator, if you would use the override keyword and an operator, the code will not compile, because the compiler expects a string value for a method name. Normally the static keyword makes a method or property shared between instances of an object. (I will explain this in another article soon). Because the operator is shared between instances the operator override has to be static. It also requires to be declared as public, because it has to be accessed outside of the class.

It is even possible to create an override with another signature, for instance:

   1:          public static salary operator + (salary x, double y)
   2:          {
   3:              salary retVal = new salary();
   4:              retVal.basicSalary = x.basicSalary + y;
   5:              retVal.bonus = x.bonus;
   6:
   7:              return retVal;
   8:          }

You can use the second operator with the following code:

       salary_1 += 100;