C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Details: With the operator keyword, public static operator methods used by the compiler when the designated operators are encountered.
KeywordsReturn: The methods return an instance of Widget. They receive 2 or 1 parameters—for binary (+) or unary (++).
Main: Here a new Widget instance is created and it uses the increment ++ operator. Its value is increased by 1, two times.
IncrementNext: Another Widget is created. And finally we add the 2 widgets together with a single "+" operator.
So: When we add the 2 Widgets together, a new Widget is returned. This is conceptually the same way the string type works.
C# program that uses operator keyword
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
Unary operators you can overload
+
-
!
~
++
--
true
false
Binary operators you can overload
+
-
*
/
%
&
|
^
<<
>>
==
!=
>
<
>=
<=
Example: In the .NET Framework itself, the string type has overloads and these are useful (this is how concatenation works).
Stringsstring.ConcatThus: If you have a type that will be used in many places, then overloading it could be a good idea.