Stats

Contributors: 10 Friday, September 30, 2016
Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Rip Tutorial: riptutorial@gmail.com
Roadmap: roadmap

Overloadable Operators

Download c# eBook

Example

C# allows user-defined types to overload operators by defining static member functions using the operator keyword.
The following example illustrates an implementation of the + operator.

If we have a Complex class which represents a complex number:

public struct Complex
{
    public double Real { get; set; }
    public double Imaginary { get; set; }
}

And we want to add the option to use the + operator for this class. i.e.:

Complex a = new Complex() { Real = 1, Imaginary = 2 };
Complex b = new Complex() { Real = 4, Imaginary = 8 };
Complex c = a + b;

We will need to overload the + operator for the class. This is done using a static function and the operator keyword:

public static Complex operator +(Complex c1, Complex c2)
{
   return new Complex 
   { 
       Real = c1.Real + c2.Real,
       Imaginary = c1.Imaginary + c2.Imaginary 
   };
}

Operators such as +, -, *, / can all be overloaded. This also includes Operators that don't return the same type (for example, == and != can be overloaded, despite returning booleans) The rule below relating to pairs is also enforced here.

Comparison operators have to be overloaded in pairs (e.g. if < is overloaded, > also needs to be overloaded).

A full list of overloadable operators (as well as non-overloadable operators and the restrictions placed on some overloadable operators) can be seen at MSDN - Overloadable Operators (C# Programming Guide).

7.0

overloading of operator is was introduced with the pattern matching mechanism of C# 7.0. For details see Pattern Matching

Given a type Cartesian defined as follows

public class Cartesian
{
    public int X { get; }
    public int Y { get; }
}   

An overloadable operator is could e.g. be defined for Polar coordinates

public static class Polar
{
    public static bool operator is(Cartesian c, out double R, out double Theta)
    {
        R = Math.Sqrt(c.X*c.X + c.Y*c.Y);
        Theta = Math.Atan2(c.Y, c.X);
        return c.X != 0 || c.Y != 0;
    }
}

which can be used like this

var c = Cartesian(3, 4);
if (c is Polar(var R, *))
{
    Console.WriteLine(R);
}

(The example is taken from the Roslyn Pattern Matching Documentation)