Skip to content
Tutorials Center
My learning

Topics

Lesson 65 of 182 ยท Classes and Objects

Operator Overloading and Conversions

Learn C# operator overloading - arithmetic, comparison and equality operators, implicit and explicit conversions, true/false, checked operators and C# 14 compound assignment operators.

When you write 2 + 3 the compiler knows what to do. When you write price1 + price2 and both are your own Money type, it does not, unless you teach it. Operator overloading lets a type define what +, -, ==, < and other operators mean for its instances. Done well, code reads like mathematics: velocity * time, start + duration, a == b. Done badly, it hides surprising behaviour behind innocent-looking symbols.

This lesson shows the syntax, the rules the compiler enforces (pairs of operators, which operators you may overload), user-defined conversions with implicit and explicit, the true/false operators, checked operators, and the C# 14 feature that lets += modify an object in place. We build a small Vector2 type as the running example. If you have not yet read about structs, it is worth doing so first, because most overloaded types are small value types.

The syntax: static operator methods

An operator overload is a public static method named operator followed by the symbol. At least one parameter must be the type that declares it.

C# A Vector2 with + and -

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Several things to notice:

  • - appears twice: with two parameters it is subtraction, with one it is negation. The compiler picks by the number of operands.
  • * is overloaded twice with the parameters in both orders. a * 3 and 3 * a are different expressions, so you provide both if you want both to work.
  • The result type is up to you. Vector2 * double gives a Vector2, but DateTime - DateTime in the standard library gives a TimeSpan.
  • Operators are resolved at compile time from the static types of the operands. They are not virtual, so they do not take part in polymorphism.

Operators on built-in types such as int + int cannot be changed. And you cannot invent new symbols: only the existing operators are available.

Which operators can be overloaded

Group Operators
Unary +x -x !x ~x ++ -- true false
Binary arithmetic and bitwise + - * / % & | ^ << >> >>>
Comparison (must come in pairs) == with !=, < with >, <= with >=
Conversions implicit, explicit
Compound assignment (C# 14) += -= *= /= %= &= |= ^= <<= >>= >>>= ++ --

Not overloadable: =, &&, ||, ??, ?., ., ?:, new, is, as, typeof, sizeof, and indexing [] (use an indexer instead). The short-circuit operators && and || are built from &, | and the true/false operators, as shown below.

The compound assignments +=, -= and the others are normally not overloaded separately: a += b simply means a = a + b and uses your +. The ++ and -- operators work the same way: you write one method and the compiler uses it for both the prefix and postfix forms.

Comparison and equality operators come in pairs

If you define == you must also define !=; if you define < you must define >; the same for <= and >=. The compiler gives error CS0216 otherwise. And if you define ==, the compiler also warns (CS0660 and CS0661) when you forget to override Equals and GetHashCode, because the three must agree. See the object class for the full contract.

The standard way to get ordering is to implement IComparable<T> once and build the four relational operators on top of it:

C# Equality and ordering operators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

All the operators delegate to two methods, so the logic lives in one place. Note that 1.10 sorts after 1.4, because the minor number is an integer, not a decimal fraction.

If you overload == on a class, inside the overload do not write a == b: that calls itself forever. Use ReferenceEquals(a, b) or a is null checks. Prefer a record or record struct and let the compiler write all of this for you (see records).

Conversions: implicit and explicit

A user-defined conversion operator tells the compiler how to turn one type into another. There are two flavours, and the difference is a promise you make to the reader:

  • implicit: the conversion always succeeds and loses no information. The compiler applies it silently wherever needed.
  • explicit: the conversion may fail or lose data. The caller must write a cast, (Target)value, which makes the risk visible.
C# Implicit and explicit conversions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Look at the line Celsius fromNumber = 100;. (We print it through interpolation on purpose: Console.WriteLine(fromNumber) would pick the double overload through the implicit conversion and print just 100.) It compiles because int converts to double first and then the implicit operator takes a double. The compiler allows one user-defined conversion, optionally surrounded by built-in ones.

Also look at the design flaw I left in on purpose: the double -> Celsius conversion is declared implicit, but it can throw for -300. That breaks the promise. A conversion that can throw should be explicit. A good rule of thumb: if you would be unhappy to see the conversion happen without a cast, make it explicit.

Rules for conversion operators:

  • One of the two types must be the declaring type, and you cannot convert to or from object, an interface, or a base or derived class (use ordinary casts for those).
  • They are chosen at compile time, like all operators.
  • Each pair of types can have at most one conversion operator in one direction.
  • They are also applied to nullable versions automatically (Celsius? to double?) when the type is a struct, a so-called lifted conversion.

Real examples from the library: decimal has implicit conversions from int and explicit ones to and from double; string converts implicitly to ReadOnlySpan<char>.

true, false and short-circuit operators

You rarely need this, but it explains how && can work for custom types. If a type defines the true and false operators plus & (or |), then a && b is evaluated as false(a) ? a : (a & b). A more common use is to make an object usable directly in an if:

C# true and false operators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

This compiles and works, but think twice: if (basket) is far less readable than if (basket.HasItems). A named property almost always wins.

checked operators and unsigned right shift

Arithmetic on int is unchecked by default and overflows silently. If your type wraps similar arithmetic, you can provide a second overload that is used inside checked contexts (C# 11):

C# checked operators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The first sum prints Small { Value = 4 }, because 260 wraps to 4 in a byte. Inside checked(...) the compiler calls the second overload, which throws. If you provide a checked version you must also provide the ordinary one. The same C# 11 release added the >>> operator (unsigned right shift) as an overloadable operator.

C# 14: user-defined compound assignment

Until C# 14, a += b always meant a = a + b: allocate a new object, then replace the variable. For a big mutable type such as a matrix or a buffer, that wasteful copy is the only choice. C# 14 lets a type define += itself as an instance method that mutates this and returns nothing:

C# In-place compound assignment (C# 14)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

If Totals only had a static operator +, then total += 5 would create a new Totals, alias would still point to the old one, and alias.Sum would not change. With the instance operator, both variables see 12. This is a language feature of C# 14 and .NET 10; older compilers reject the syntax. Rules: the operator is an instance method, public, returns void, takes one parameter, and has the name of the compound operator (+=, -=, *= and so on, plus ++ and -- in instance form). Use it for large, mutable, reference-type objects where allocating a result per operation is the bottleneck. For small immutable values keep the plain static operators.

Design guidelines

  1. Mirror what everyone expects. + should be addition-like and symmetric where possible; == must agree with Equals; < must give a consistent ordering. Do not make + on a Customer mean "merge".
  2. Provide named alternatives. Languages that lack operators, and people who search for "add", will look for Add, Subtract, Negate. The .NET guidelines recommend a named method next to every operator (Vector2.Add). Generic code can also use generic math interfaces instead.
  3. Keep types immutable (readonly struct or record), so that a + b never changes a.
  4. Overload only for value-like types: vectors, money, complex numbers, ranges, units, big numbers. Rarely for entities.
  5. Make lossy conversions explicit.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which signature correctly overloads the plus operator for a type Money?

    Operators are public static methods whose return type comes first, then the keyword operator and the symbol.
  2. 2. What happens if you overload == but not !=?

    The compiler requires matching pairs for ==/!=, </>, and <=/>= (error CS0216).
  3. 3. When should a conversion operator be declared explicit?

    Explicit conversions require a cast, which warns the reader. Implicit conversions must be safe and lossless.
  4. 4. What does the C# 14 declaration public void operator +=(int amount) provide?

    User-defined compound assignment operators are instance methods returning void that mutate this, which avoids allocating a new object.
  5. 5. Why can you not overload && directly?

    a && b is evaluated using the false operator and &, so you customise it by defining those instead.

Summary

  • Operators are public static methods named operator <symbol>; at least one parameter must be the declaring type.
  • ==/!=, </> and <=/>= must be declared in pairs, and == must agree with Equals and GetHashCode.
  • implicit conversions must be lossless and safe; anything else is explicit.
  • Provide checked operator versions for overflow-sensitive arithmetic, and use C# 14 instance compound operators (void operator +=) to update big objects in place.
  • Keep operator meanings natural, types immutable, and offer named method alternatives.

Next: Indexers and Custom Iterators