Operator Overloading Best Practices
Keep overloaded operators intuitive.
Best Practices for Operator Overloading
Operator overloading is a sharp tool. Used well it makes value types intuitive; used poorly it makes code cryptic. This lesson covers principles that keep overloaded operators predictable.
Only Overload When Meaning Is Obvious
Overload an operator only when its meaning is unambiguous for your type. + on a vector clearly means component-wise addition; + on an Order would just confuse readers.
using System;
public struct Vector2
{
public int X, Y;
public Vector2(int x, int y) { X = x; Y = y; }
// + means adding components: obvious and expected
public static Vector2 operator +(Vector2 a, Vector2 b)
=> new Vector2(a.X + b.X, a.Y + b.Y);
public override string ToString() => "(" + X + ", " + Y + ")";
}
public class Program
{
public static void Main()
{
Console.WriteLine(new Vector2(1, 2) + new Vector2(3, 4));
}
}All lessons in this course
- Overloading Arithmetic Operators
- Overloading Comparison Operators
- User-Defined Conversions
- Operator Overloading Best Practices