Advertisement
Beginner C#, Indexers & Operator Overloading

How do you overload the '+' operator to support adding two custom objects together?

Short answer

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.

Save C# mock interview
Advertisement
AModel answer
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); // 15
Real-world example
Allowing two Money, Vector, or Complex number instances to be combined naturally with the '+' operator instead of a named method.
Likely follow-ups
  • Why must operator overloads always be declared as 'public static' members?
Related topics