C# › Indexers & Operator Overloading
How do you overload the '+' operator to support adding two custom objects together?
BeginnerAnswer
Declare a 'public static' method named 'operator +' taking two parameters of your type (or your type and another compatible type), returning the result — the compiler then lets you use the normal '+' syntax directly on instances of your type.
public struct Money {
public decimal Amount;
public static Money operator +(Money a, Money b) => new Money { Amount = a.Amount + b.Amount };
}
Money total = new Money { Amount = 10 } + new Money { Amount = 5 };
Console.WriteLine(total.Amount); // 15Real-world example Allowing two Money, Vector, or Complex number instances to be combined naturally with the '+' operator instead of a named method.