Skip to content

Operator Overloading

Mario Gutierrez edited this page Jan 7, 2017 · 1 revision

Various operators in C# can be overloaded.

public static Point operator + (Point p1, Point p2)
{
  return new Point(p1.x + p2.x, p1.y + p2.y);
}

With binary operators, you get the corresponding assignment operator for free. For example, with the above example you also get '+='.

Both operands don't have to be the same type.

public static Point operator * (Point p1, float scalar)
{
  return new Point(p1.x * scalar, p1.y * scalar);
}

If you do this though, do it both ways to support commutativity.

public static Point operator * (float scalar, Point p1)
{
  return new Point(p1.x * scalar, p1.y * scalar);
}

You can override some unary operators, such as ++.

public static Point operator ++ (Point p)
{
  return new Point(p.x + 1, p.y + 1);
}

In C++ you can override the pre/post increment/decrement operators separately. In C# you can't, but you get the correct behavior for free.

Clone this wiki locally