Most of the built-in operators that are available in C# can be redefined. In todays article, I’ll be showing you how you can redefine operators to match your custom classes. Additionally, I’ll cover which operators actually can be overwritten.

Redefining Operators

To create custom functionality for operators in combination with your own classes, you’ll simply need to create methods matching a specific pattern. These methods require the usage of the keyword operator, followed by the actual operator you’ll want to overwrite.

I’ve created a simple class to demonstrate the concept of operator overloading. This class represents a rectangle, which only has the two properties Length and Width.

public class Rectangle
{
    public double Length { get; set; }
    public double Width { get; set; }
}

I’d like to start by overloading the + operator. When this is applied to two rectangles, I want to receive a new rectangle where both width and length from both input objects are added. You achieve this functionality by adding the following method to the class Rectangle.

public static Rectangle operator + (Rectangle a, Rectangle b)
{
    return new Rectangle { Length = a.Length + b.Length, Width = a.Width + b.Width };
}

Quite easy, isn’t it? But of course, you’re not restricted to these simple operators, which is why I’ll cover all of the available operators in the next section.

Another example I’d like to demonstrate is the comparison of two objects. In the following listing, you can see the comparison of two Rectangle objects with the operators == and !=.

public static bool operator == (Rectangle a, Rectangle b)
{
    return (a.Length == b.Length && a.Width == b.Width);
}

public static bool operator != (Rectangle a, Rectangle b)
{
    return (a.Length != b.Length || a.Width != b.Width);
}

(Non-)Overloadable Operators

Altough a lot of operators can be overloaded, there are some exceptions. To give you a better understanding and overview of allowed operators, I’ve listed them in the table below.

Operator Description Overloadable
+, -, *, / Basic arithmetic operations
++, — Increment / Decrement
~ Bitwise complement
==, !=, <, >, <=, >= Comparison
&&, || Conditional logical operators
+=, -=, *=, /=, %= Assignment Operators