Overloading Arithmetic Operators
Define +, -, * for your own types.
Why Overload Arithmetic Operators?
Operator overloading lets your own types use familiar symbols like +, -, and *. For value-like types such as vectors, money, or complex numbers, this makes code read like math instead of method calls.
The operator + Syntax
An overloaded operator is declared as a public static method whose name is operator followed by the symbol. At least one parameter must be the containing type.
using System;
public struct Vector2
{
public int X, Y;
public Vector2(int x, int y) { X = x; Y = y; }
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()
{
var sum = new Vector2(1, 2) + new Vector2(3, 4);
Console.WriteLine(sum);
}
}All lessons in this course
- Overloading Arithmetic Operators
- Overloading Comparison Operators
- User-Defined Conversions
- Operator Overloading Best Practices