Operator Overloading in C#
Operator overloading enables custom behavior for operators when working with user-defined types. Key aspects include:
- Only applicable to classes and structs
- Implemented through static methods named
operatorfollowed by the symbol (e.g.,operator +) - Must be members of the class/struct they operate on
Syntax Patterns
Unary operators (single operand):
public static CustomType operator -(CustomType operand)
{
return new CustomType(-operand.Value);
}
Binary operators (two operands, at least one must be the containing type):
public static CustomType operator -(CustomType left, CustomType right)
{
return new CustomType(left.Value - right.Value);
}
Practical Example
class BoundedNumber
{
private const int Max = 100;
private const int Min = 0;
private int _value;
public int Value
{
get => _value;
set => _value = Math.Clamp(value, Min, Max);
}
public BoundedNumber(int value = 0) => Value = value;
// Unary negation
public static BoundedNumber operator -(BoundedNumber num)
{
return new BoundedNumber(-num.Value);
}
// Subtraction
public static BoundedNumber operator -(BoundedNumber a, BoundedNumber b)
{
return new BoundedNumber(a.Value - b.Value);
}
// Double addition
public static BoundedNumber operator +(BoundedNumber num, double add)
{
return new BoundedNumber(num.Value + (int)add);
}
}
Operator Overloading Constraints
| Unary Operatros | Binary Operators |
|---|---|
+, -, !, ~, ++, --, true, false |
`+, -, *, /, %, &, |
Restrictions:
- Cannot create new operators
- Cannot modify operattor syntax
- Cannot alter behavior for built-in types
- Cannot change operator precedence
Special Considerations for Increment/Decrement
For reference types:
- Prefix (
++x) modifies and returns the original object - Postfix (
x++) modifies the original but returns a reference to the modified object
class Counter
{
public int Count { get; set; }
public static Counter operator ++(Counter c)
{
c.Count++;
return c;
}
}
var counter = new Counter { Count = 1 };
Console.WriteLine(counter++.Count); // Outputs 2 (modified value)