Overloadable Operators

suggest change

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).

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);
}

This example is taken from the Roslyn Pattern Matching Documentation.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Operators:
* Syntax
* Overloadable Operators
* sizeof
* typeof

Table Of Contents
2 Operators
17 Regex
19 Arrays
21 Enum
22 Tuples
24 GUID
27 Looping
36 Casting
46 Methods
88 Events
92 Structs
104 Indexer
106 Stream
107 Timers
109 Threading
127 Caching
135 Pointers
147 C# Script