How to Overload Operator in C#: Syntax and Example
In C#, you overload an operator by defining a
public static method named operator followed by the operator symbol inside your class or struct. This method must take the appropriate parameters and return the result type, allowing you to customize how operators like + or == work for your types.Syntax
To overload an operator in C#, define a public static method inside your class or struct with the name operator followed by the operator symbol. The method must have parameters matching the operator's operands and return the result type.
- public static: Required modifiers
- return type: The type returned by the operator
- operator symbol: The operator you want to overload (e.g., +, -, ==)
- parameters: The operands for the operator
csharp
public static ReturnType operator OperatorSymbol(Type1 operand1, Type2 operand2) { // implementation }
Example
This example shows how to overload the + operator for a Point class to add two points by summing their X and Y coordinates.
csharp
using System; public class Point { public int X { get; } public int Y { get; } public Point(int x, int y) { X = x; Y = y; } public static Point operator +(Point a, Point b) { return new Point(a.X + b.X, a.Y + b.Y); } public override string ToString() => $"({X}, {Y})"; } 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)
Common Pitfalls
Common mistakes when overloading operators include:
- Not declaring the operator method as
public static. - Using incorrect parameter types or counts.
- Forgetting to return a value.
- Not overloading related operators together (e.g., if you overload
==, also overload!=). - Overloading operators in a way that confuses users or breaks expected behavior.
csharp
/* Wrong: Missing static modifier */ // public Point operator +(Point a, Point b) { ... } // Error /* Correct: */ public static Point operator +(Point a, Point b) { return new Point(a.X + b.X, a.Y + b.Y); }
Quick Reference
Here are some common operators you can overload in C#:
| Operator | Description |
|---|---|
| + | Addition |
| - | Subtraction |
| * | Multiplication |
| / | Division |
| == | Equality |
| != | Inequality |
| < | Less than |
| > | Greater than |
| <= | Less than or equal |
| >= | Greater than or equal |
| ++ | Increment |
| -- | Decrement |
| true | True operator for conditional checks |
| false | False operator for conditional checks |
Key Takeaways
Operator overloading in C# requires a public static method named operator followed by the operator symbol.
The method must have parameters matching the operator's operands and return the correct result type.
Always overload related operators together to maintain consistent behavior.
Avoid confusing or unexpected operator behavior to keep your code clear and maintainable.
Test your overloaded operators to ensure they behave as intended.