
Overloaded operators sometimes improve program syntax. With the operator keyword, you declare public static operator methods that are used by the compiler when the designated operators are encountered. If your C# code is used by many developers, this can make programs easier to understand and shorter.
KeywordsThis C# example program uses the operator keyword. It overloads operators.

This program declares a Widget class. Here, Widgets can be added together or incremented with the same syntax used for integers. In the Widget class, we provide two public static methods: operator +, and operator ++. They both return an instance of Widget. They receive two or one formal parameters depending on whether the operator is binary (+) or unary (++).
Program that uses operator keyword [C#]
using System;
class Widget
{
public int _value;
public static Widget operator +(Widget a, Widget b)
{
// Add two Widgets together.
// ... Add the two int values and return a new Widget.
Widget widget = new Widget();
widget._value = a._value + b._value;
return widget;
}
public static Widget operator ++(Widget w)
{
// Increment this widget.
w._value++;
return w;
}
}
class Program
{
static void Main()
{
// Increment widget twice.
Widget w = new Widget();
w++;
Console.WriteLine(w._value);
w++;
Console.WriteLine(w._value);
// Create another widget.
Widget g = new Widget();
g++;
Console.WriteLine(g._value);
// Add two widgets.
Widget t = w + g;
Console.WriteLine(t._value);
}
}
Output
1
2
1
3
Using Widget operators. Now look at the Main() entry point. A new Widget instance is created and it uses the increment ++ operator. Its value is increased by one; then we increase it by one again. Next, another Widget is created and finally we add the two widgets together. When we add the two Widgets together, a new Widget is returned. This is conceptually the same way the string type works.
Many but not all operators in the C# language can be overloaded. I borrowed this list from the C# specification, which has more in-depth information on overloading some of these operators.
Unary operators you can overload + - ! ~ ++ -- true false Binary operators you can overload + - * / % & | ^ << >> == != > < >= <=

Is it necessary to overload operators on every class you create? Absolutely not. My opinion is that overloading operators is best done very rarely and only on types that are very important and commonly used. In the .NET Framework itself, the string type has overloads and these are useful. If you have a type that will be used in thousands of places, then overloading it could be a good idea if those overloads make intuitive sense.

This example looked at the operator keyword in the C# programming language and its usage for overloading binary and unary operators. We provided a compile-ready example of operator overloading and also reproduced a list of all the overloadable operators in this language.
Class Examples