C sharp - Overloading Binary Operators in C#
Operator overloading allows you to redefine the behavior of binary operators (like +, -, *, etc.) for user-defined types (typically classes and structs).
Basic Syntax
To overload a binary operator, define a public static method using the operator keyword.
public static ReturnType operator <operator>(Type lhs, Type rhs)
-
ReturnType: The type the operation returns. -
lhsandrhs: Left-hand and right-hand side operands. -
<operator>: The operator you want to overload (e.g.,+,-,*,/,==, etc.).
Example: Overloading + Operator
Let's create a Point class that adds two points:
class Program
{
static void Main()
{
Point p1 = new Point(2, 3);
Point p2 = new Point(4, 5);
Point p3 = p1 + p2;
Console.WriteLine(p3); // Output: (6, 8)
}
}
Other Common Binary Operators You Can Overload
| Operator | Purpose |
|---|---|
+ |
Addition |
- |
Subtraction |
* |
Multiplication |
/ |
Division |
% |
Modulus |
==, != |
Equality / Inequality |
<, > |
Less than / Greater than |
<=, >= |
Less than or equal / Greater than or equal |
Note: When you overload ==, you must also overload !=, and usually override Equals() and GetHashCode() for consistency.
Rules and Restrictions
-
Only classes or structs can overload operators.
-
You cannot overload operators for built-in types (like
int,double). -
You must declare operator methods as
public static. -
You cannot overload logical operators like
&&and||directly unless you also overload&and|.