Skip to content
Homeβ€Ί C# / .NETβ€Ί C# Operator Overloading: No GetHashCode Breaks HashSet

C# Operator Overloading: No GetHashCode Breaks HashSet

Where developers are forged. Β· Structured learning Β· Free forever.
πŸ“ Part of: OOP in C# β†’ Topic 8 of 10
A missing GetHashCode when overloading operator== caused duplicate HashSet entries in payment reconciliation, wasting hours.
βš™οΈ Intermediate β€” basic C# / .NET knowledge assumed
In this tutorial, you'll learn
A missing GetHashCode when overloading operator== caused duplicate HashSet entries in payment reconciliation, wasting hours.
  • Operator overloading compiles to a static method named op_Addition, op_Equality, etc. β€” it's ordinary method dispatch with no hidden magic or runtime cost.
  • Overloading == forces you to also overload != (compiler error otherwise), and you must override Equals + GetHashCode to stay consistent with LINQ, Dictionary, and HashSet behaviour.
  • Compound assignment operators (+=, -=, *=) are automatically synthesised by the compiler once you define the base operator β€” you never write them yourself, and attempting to do so is a compile error.
✦ Plain-English analogy ✦ Real code with output ✦ Interview questions
⚑Quick Answer
  • Operator overloading lets your structs and classes use C# operators (+, ==, etc.) naturally.
  • It's syntactic sugar over static methods β€” the compiler translates a + b to operator+.
  • Compound assignment (+=, -=) is auto-derived from the base operator.
  • Overloading == forces you to also overload != and override Equals + GetHashCode.
  • Implicit conversions require lossless safety; explicit conversions signal possible data loss.
🚨 START HERE

Operator Overloading Quick Debug Cheat Sheet

Five operator-related failures and the exact fix
🟑

HashSet allows duplicates after overloading ==

Immediate ActionRun a quick test: create two equal objects and check if hashSet.Contains(second) returns false.
Commands
Inspect the type: `typeof(MyType).GetMethods() | Where-Object { $_.Name -match 'GetHashCode|Equals' }`
Check if GetHashCode uses all fields: `HashCode.Combine(Field1, Field2)`
Fix NowAdd GetHashCode override using HashCode.Combine.
🟑

Compile error: 'Operator == requires matching operator !='

Immediate ActionRead the exact error β€” it tells you which operator is missing.
Commands
Search for `operator ==` in file, then add `public static bool operator !=(...) => !(...left.Equals(right));`
Verify the pair compiles: `csc /target:library MyFile.cs`
Fix NowAdd the missing operator overload.
🟑

Implicit conversion caused unexpected method resolution

Immediate ActionIsolate the line where the conversion happens, inspect parameter types.
Commands
Change implicit to explicit in the type definition, then fix all call sites.
Use Roslyn analyser: `dotnet build /warnaserror:CS1061,CS1501` to surface hidden overload resolution.
Fix NowMake conversion explicit unless it's truly lossless.
🟑

+= does not compile for a struct

Immediate ActionCheck if the struct is marked readonly. If not, make it readonly.
Commands
Add `readonly` modifier to the struct declaration.
Remove any mutable fields; use readonly properties.
Fix NowChange to readonly struct – += will then work by assigning a new copy.
🟑

Dynamic dispatch bypasses overloaded operator

Immediate ActionCheck if a variable is typed as `dynamic` or `object`.
Commands
Replace `dynamic` with the concrete type, or use `switch` pattern matching.
If using object, cast to the concrete type before using operator.
Fix NowAvoid dynamic/object for types with overloaded operators.
Production Incident

The Missing GetHashCode That Broke Payment Reconciliation

A fintech company's nightly reconciliation job failed silently because Money structs with the same value were stored in separate HashSet buckets. The root cause? Overloaded == but no GetHashCode override.
SymptomPayment reconciliation ran nightly: it collected all transaction amounts into a HashSet<Money>, expected deduplication, but ended up with duplicates. The HashSet.Count was always higher than expected, causing mismatches that took hours to track down.
AssumptionThe team assumed that overloading == and implementing IEquatable<Money> would be sufficient for HashSet deduplication. They read that HashSet uses GetHashCode internally but didn't realize the compiler enforces consistency β€” and the warning CS0659 was dismissed as a false positive.
Root causeMoney struct had operator== and Equals overridden, but GetHashCode was not overridden. Two Money objects with same amount and currency returned different hash codes (the default from struct’s value-based hash was unreliable across runs). HashSet placed equal objects into different buckets, so Contains() returned false and duplicates were allowed.
FixOverride GetHashCode using HashCode.Combine(Amount, Currency) and add IEquatable<Money>. Rebuild the HashSet β€” the Count dropped to expected values and reconciliation matched.
Key Lesson
Overriding == without GetHashCode is a data-corruption bug, not a warning.Treat compiler warning CS0659 as a hard error.Always implement IEquatable<T> on structs to avoid boxing.Test your type in a HashSet before production.
Production Debug Guide

Symptom β†’ Action pairs for the most common operator overloading bugs

HashSet contains duplicate elements, Dictionary lookup fails even though key exists→Check if type overrides GetHashCode. Open the type definition: if GetHashCode is missing or uses default struct implementation, override it using HashCode.Combine.
Compile error CS0216: 'type' requires matching operator '!=' to also be defined→C# enforces that == and != must be overloaded as a pair. Add the missing operator. Usually delegate to !left.Equals(right).
Implicit conversion results in wrong method overload being called→Too many implicit conversions cause ambiguity errors or silent wrong calls. Change implicit to explicit using (ExplicitType)value at call sites, or add a diagnostic overload.
operator+ works but += fails: 'the left-hand side of an assignment must be a variable'β†’If the type is a class, += tries to mutate the original reference. Ensure the type is a readonly struct so compound assignment returns a new instance that can be assigned.
Comparing two equal Money structs returns false when using == in a generic method→Generic methods use object.Equals at runtime, not operator==. Override Equals and GetHashCode, and constrain generic types with IEquatable<T>.

Most C# developers use operators every day without thinking about it β€” adding integers, comparing strings, concatenating values. But the moment you build your own types, those same operators go silent. Try adding two Money objects or comparing two Temperature readings and the compiler stares back at you blankly. That friction is exactly the gap operator overloading was designed to close.

The problem isn't just syntax inconvenience. When your custom type can't use natural operators, callers are forced to write verbose method calls like moneyA.Add(moneyB) instead of moneyA + moneyB. That noise accumulates fast, and it breaks the mental model your type is trying to create. A Vector3 that requires vector.CrossProduct(other) instead of vector * other doesn't feel like a vector β€” it feels like a bag of helper methods. Operator overloading lets your type fulfill its conceptual promise.

By the end of this article you'll understand exactly which operators C# lets you overload and which it forbids, why certain pairs must always be overloaded together, how to implement a real-world Money struct that supports arithmetic and equality cleanly, and the three mistakes that trip up even experienced developers. You'll also walk away ready to answer the operator overloading questions that regularly show up in .NET interviews.

What Operator Overloading Actually Does Under the Hood

When you write 5 + 3 in C#, the compiler translates that into a call to a static method. For built-in types the runtime handles this invisibly, but the mechanism is the same one you use for your own types. Operator overloading is just declaring a special static method with the keyword operator followed by the symbol you're targeting.

The compiler sees moneyA + moneyB, looks for a public static method on the Money type with the signature operator+(Money, Money), and calls it. If it can't find one, you get a compile-time error β€” not a runtime crash, which is a nice safety net.

This means there's no magic and no performance penalty beyond a normal static method call. The JIT compiler inlines these calls the same way it does any other small static method, so you're not sacrificing speed for readability.

The key constraint is that at least one parameter must be of the type you're defining. You can't hijack the behaviour of int + int from inside your own class. C# specifically protects built-in type semantics from being overridden by user code.

OperatorBasics.cs Β· CSHARP
12345678910111213141516171819202122232425262728293031323334353637383940414243444546
using System;

// A simple struct representing a temperature reading
public struct Temperature
{
    public double Celsius { get; }

    public Temperature(double celsius)
    {
        Celsius = celsius;
    }

    // The compiler turns 'temp1 + temp2' into this static method call.
    // Both parameters must relate to our type β€” here both ARE our type.
    public static Temperature operator +(Temperature left, Temperature right)
    {
        return new Temperature(left.Celsius + right.Celsius);
    }

    // Scalar multiplication: allow 'temperature * factor'
    // One parameter is our type, the other is double β€” that's allowed.
    public static Temperature operator *(Temperature temp, double factor)
    {
        return new Temperature(temp.Celsius * factor);
    }

    // Override ToString so our output is readable
    public override string ToString() => $"{Celsius:F1}Β°C";
}

class Program
{
    static void Main()
    {
        var morningTemp = new Temperature(18.5);
        var afternoonRise = new Temperature(6.0);

        // This calls operator+ behind the scenes
        Temperature peakTemp = morningTemp + afternoonRise;
        Console.WriteLine($"Peak temperature: {peakTemp}");

        // This calls operator* β€” scalar scaling
        Temperature doubled = morningTemp * 2.0;
        Console.WriteLine($"Doubled morning: {doubled}");
    }
}
β–Ά Output
Peak temperature: 24.5Β°C
Doubled morning: 37.0Β°C
πŸ”₯Under the Hood:
Open the compiled assembly in IL Spy or SharpLab.io and you'll see operator+ compiled to a method named op_Addition. That's the CLS-compliant name the runtime uses. Other languages like F# can call your overloaded operators using these method names directly, which is why naming rules are enforced by the spec.
πŸ“Š Production Insight
JIT inlines small operator methods, so there's zero runtime overhead compared to hand-written static methods.
But if your operator method does more than a simple arithmetic operation (e.g., database calls, validation), inlining is suppressed β€” profiler shows the cost.
Rule: keep operator bodies lean and side-effect-free for the compiler to optimize.
🎯 Key Takeaway
Operator overloading is purely syntactic sugar for a static method.
The compiler enforces type safety β€” no surprise overloads from other types.
There is zero runtime penalty when the operator is small and JIT-inlinable.

Building a Real-World Money Type β€” Arithmetic and Equality Done Right

The most convincing demo of operator overloading isn't a math vector β€” it's a Money type. Money has rules that match how operators feel: you can add two USD amounts, but adding USD to EUR should throw. That real-world constraint shows you how to put business logic inside an operator, not just delegate to a constructor.

Equality is where most developers stumble. C# has two separate equality concepts: reference equality (are these the same object in memory?) and value equality (do these represent the same value?). For a struct, the default == checks value equality field-by-field using reflection, which is both slow and fragile. For a class, the default == is reference equality, which is almost never what you want for a value-oriented type like Money.

The rule is non-negotiable: if you overload ==, you MUST also overload !=. The compiler enforces this. And whenever you overload ==, you should also override Equals(object) and GetHashCode(), because LINQ, dictionaries, and HashSets all rely on those methods, not on your operator.

This section shows a complete Money struct that gets all of this right, so you have a real template to copy from.

Money.cs Β· CSHARP
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
using System;
using System.Collections.Generic;

public readonly struct Money : IEquatable<Money>
{
    public decimal Amount { get; }
    public string Currency { get; }

    public Money(decimal amount, string currency)
    {
        if (string.IsNullOrWhiteSpace(currency))
            throw new ArgumentException("Currency code cannot be empty.", nameof(currency));

        Amount = Math.Round(amount, 2); // Money is always 2 decimal places
        Currency = currency.ToUpperInvariant();
    }

    // ── Arithmetic operators ────────────────────────────────────────────

    public static Money operator +(Money left, Money right)
    {
        // Business rule lives HERE, not scattered across callers
        EnsureSameCurrency(left, right, "+");
        return new Money(left.Amount + right.Amount, left.Currency);
    }

    public static Money operator -(Money left, Money right)
    {
        EnsureSameCurrency(left, right, "-");
        return new Money(left.Amount - right.Amount, left.Currency);
    }

    // Scale by a factor β€” e.g. applying a tax rate
    public static Money operator *(Money money, decimal factor)
    {
        return new Money(money.Amount * factor, money.Currency);
    }

    // Allow factor * money as well (commutativity for the caller's convenience)
    public static Money operator *(decimal factor, Money money) => money * factor;

    public static bool operator >(Money left, Money right)
    {
        EnsureSameCurrency(left, right, ">");
        return left.Amount > right.Amount;
    }

    public static bool operator <(Money left, Money right)
    {
        EnsureSameCurrency(left, right, "<");
        return left.Amount < right.Amount;
    }

    // ── Equality operators ──────────────────────────────────────────────
    // Rule: overload == β†’ must also overload !=
    // Rule: overload == β†’ must also override Equals and GetHashCode

    public static bool operator ==(Money left, Money right) => left.Equals(right);
    public static bool operator !=(Money left, Money right) => !left.Equals(right);

    // IEquatable<Money> β€” used by List.Contains, LINQ, etc. without boxing
    public bool Equals(Money other)
        => Amount == other.Amount &&
           string.Equals(Currency, other.Currency, StringComparison.OrdinalIgnoreCase);

    // Required override when Equals is overridden β€” used by dictionaries/hashsets
    public override bool Equals(object? obj)
        => obj is Money other && Equals(other);

    public override int GetHashCode()
        => HashCode.Combine(Amount, Currency.ToUpperInvariant());

    public override string ToString() => $"{Currency} {Amount:F2}";

    // ── Private helpers ─────────────────────────────────────────────────

    private static void EnsureSameCurrency(Money left, Money right, string op)
    {
        if (!string.Equals(left.Currency, right.Currency, StringComparison.OrdinalIgnoreCase))
            throw new InvalidOperationException(
                $"Cannot apply '{op}' to {left.Currency} and {right.Currency}. " +
                $"Convert to the same currency first.");
    }
}

class Program
{
    static void Main()
    {
        var price = new Money(19.99m, "USD");
        var shipping = new Money(4.99m, "USD");
        var taxRate = 0.08m; // 8% tax

        Money subtotal = price + shipping;          // calls operator+
        Money tax = subtotal * taxRate;              // calls operator*
        Money total = subtotal + tax;

        Console.WriteLine($"Price:    {price}");
        Console.WriteLine($"Shipping: {shipping}");
        Console.WriteLine($"Tax (8%): {tax}");
        Console.WriteLine($"Total:    {total}");
        Console.WriteLine();

        // Equality check works correctly
        var duplicatePrice = new Money(19.99m, "USD");
        Console.WriteLine($"price == duplicatePrice: {price == duplicatePrice}");
        Console.WriteLine($"price == total:          {price == total}");
        Console.WriteLine();

        // Works correctly in a HashSet because GetHashCode is consistent with Equals
        var priceSet = new HashSet<Money> { price, shipping, duplicatePrice };
        Console.WriteLine($"HashSet count (price added twice): {priceSet.Count}");
        Console.WriteLine();

        // Comparison operators
        Console.WriteLine($"total > price: {total > price}");

        // This would throw β€” different currencies
        try
        {
            var euros = new Money(10.00m, "EUR");
            var _ = price + euros;
        }
        catch (InvalidOperationException ex)
        {
            Console.WriteLine($"Expected error: {ex.Message}");
        }
    }
}
β–Ά Output
Price: USD 19.99
Shipping: USD 4.99
Tax (8%): USD 2.00
Total: USD 26.98

price == duplicatePrice: True
price == total: False

HashSet count (price added twice): 2

total > price: True
Expected error: Cannot apply '+' to USD and EUR. Convert to the same currency first.
⚠ Watch Out:
If you override Equals but forget GetHashCode, your type will silently break inside Dictionary<K,V> and HashSet<T>. Two Money values that are Equal could hash to different buckets, causing lookups to fail even when the key is logically present. The compiler will warn you (CS0659), but the bug is real and confusing β€” always override both together.
πŸ“Š Production Insight
In a real payments system, missing GetHashCode caused a reconciliation job to incorrectly flag 2% of transactions as unmatched overnight.
The bug was hard to spot because operator== alone worked fine in unit tests β€” the problem only surfaced in HashSet and Dictionary usage.
Rule: always treat compiler warning CS0659 as an error and write a unit test that exercises HashSet with a duplicate.
🎯 Key Takeaway
Overload == and != together.
Override Equals and GetHashCode together.
Implement IEquatable<T> to avoid boxing on structs.
Test your type in HashSet and Dictionary before shipping.

Which Operators You Can Overload β€” and the Ones C# Deliberately Blocks

C# gives you a generous but not unlimited set of operators to overload. The choices reflect a deliberate philosophy: operators that control program flow, assignment, or type conversion are off-limits to prevent code that's impossible to reason about.

The operators you CAN overload fall into three groups. Unary operators: +, -, !, ~, ++, --. Binary arithmetic: +, -, *, /, %, &, |, ^, <<, >>. Comparison: ==, !=, <, >, <=, >= (these must be overloaded in symmetric pairs β€” you can't overload < without also overloading >).

The operators C# deliberately BLOCKS include: &&, ||, =, +=, -=, new, typeof, is, as, and the ternary ?:. The compound assignment operators (+=, -=, etc.) are intentionally excluded because C# derives them automatically. Once you define operator+, the compiler generates += for free. You never write it yourself.

One special case worth knowing: the true and false operators. These are rarely used, but overloading them enables your type to participate in short-circuit && and || evaluation. It's an advanced pattern used in libraries that model nullable or tri-state logic.

OperatorRulesDemo.cs Β· CSHARP
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
using System;

public struct Percentage
{
    public double Value { get; } // 0.0 to 100.0

    public Percentage(double value)
    {
        // Clamp silently β€” percentages can't exceed 100% or go below 0%
        Value = Math.Clamp(value, 0.0, 100.0);
    }

    // Unary negation β€” "remaining percentage"
    // e.g. !Percentage(30) β†’ Percentage(70) means "70% remaining"
    public static Percentage operator !(Percentage p)
        => new Percentage(100.0 - p.Value);

    // Unary increment β€” nudge up by 1 point
    public static Percentage operator ++(Percentage p)
        => new Percentage(p.Value + 1.0);

    // Binary addition
    public static Percentage operator +(Percentage left, Percentage right)
        => new Percentage(left.Value + right.Value); // clamped by constructor

    // Comparison pair β€” C# REQUIRES both < and > if you want either
    public static bool operator <(Percentage left, Percentage right)
        => left.Value < right.Value;

    public static bool operator >(Percentage left, Percentage right)
        => left.Value > right.Value;

    // Equality pair β€” C# REQUIRES both == and != if you want either
    public static bool operator ==(Percentage left, Percentage right)
        => Math.Abs(left.Value - right.Value) < 0.0001; // float-safe comparison

    public static bool operator !=(Percentage left, Percentage right)
        => !(left == right);

    public override bool Equals(object? obj)
        => obj is Percentage other && this == other;

    public override int GetHashCode() => Math.Round(Value, 4).GetHashCode();

    public override string ToString() => $"{Value:F1}%";
}

class Program
{
    static void Main()
    {
        var discount = new Percentage(30.0);
        var extraOff = new Percentage(15.0);

        // += is automatically derived from operator+ β€” we never wrote it
        Percentage combined = discount;
        combined += extraOff;
        Console.WriteLine($"Combined discount: {combined}");

        // Unary ! gives us the "remaining" percentage
        Percentage customerPays = !combined;
        Console.WriteLine($"Customer pays: {customerPays}");

        // ++ operator
        Percentage bumped = discount;
        bumped++;
        Console.WriteLine($"Bumped discount: {bumped}");

        // Clamping β€” adding beyond 100% is safe
        var huge = new Percentage(80.0) + new Percentage(80.0);
        Console.WriteLine($"Clamped result: {huge}");

        // Comparison
        Console.WriteLine($"discount > extraOff: {discount > extraOff}");

        // Demonstrating that == and != must be paired
        Console.WriteLine($"discount == extraOff: {discount == extraOff}");
        Console.WriteLine($"discount != extraOff: {discount != extraOff}");
    }
}
β–Ά Output
Combined discount: 45.0%
Customer pays: 55.0%
Bumped discount: 31.0%
Clamped result: 100.0%
discount > extraOff: True
discount == extraOff: False
discount != extraOff: True
πŸ’‘Pro Tip:
You never need to define += explicitly. The moment you define operator+, C# synthesises compound assignment for free. If you try to define operator+= yourself you'll get a compile error. This is by design β€” it prevents a class where a + b and a += b could behave differently, which would be a maintenance nightmare.
πŸ“Š Production Insight
Compound assignment auto-derivation means you cannot have a += b behave differently from a + b.
This is good: it prevents a common source of bugs where the two forms diverge.
But it also means you cannot optimize += for mutable types β€” if your class is mutable and you want in-place mutation, you must not use operator overloading; use a dedicated method like AddInPlace.
🎯 Key Takeaway
C# blocks assignment, conditional, and flow-control operators for safety.
Compound assignment operators are auto-derived from base operators β€” you never write them.
Comparison operators must be overloaded in symmetric pairs.

Conversion Operators β€” Letting Your Type Speak Other Type Languages

Operator overloading has a close sibling that often gets forgotten: conversion operators. These let you define what happens when code tries to cast or implicitly assign your type to another type. There are two flavours: implicit (no cast syntax needed, compiler inserts it silently) and explicit (caller must write the cast, signalling they understand precision might be lost).

The rule of thumb is pragmatic: use implicit conversion only when it is completely safe and lossless β€” the kind of conversion where no reasonable caller would ever want to be warned. Use explicit when data can be truncated, precision is lost, or an exception might be thrown.

A great real-world example is a Celsius type that converts to Fahrenheit. That conversion is always possible but the result is a different scale, so explicit makes sense. Going the other way, converting from a raw double to Celsius, could be implicit because it's just wrapping a value with no loss.

Conversion operators compose naturally with your arithmetic operators. Once you have a rich conversion story, your type starts to feel like a first-class citizen of the language, not an awkward guest.

ConversionOperators.cs Β· CSHARP
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
using System;

public readonly struct Celsius
{
    public double Degrees { get; }

    public Celsius(double degrees) => Degrees = degrees;

    // IMPLICIT: wrapping a double in Celsius is always safe β€” no information lost
    // Caller can write: Celsius temp = 100.0;  (no cast needed)
    public static implicit operator Celsius(double degrees)
        => new Celsius(degrees);

    // EXPLICIT: converting to Fahrenheit changes the scale.
    // Caller must write: double f = (double)temp;  to acknowledge the conversion.
    // We return double because Fahrenheit is just a double to the outside world here.
    public static explicit operator double(Celsius celsius)
        => (celsius.Degrees * 9.0 / 5.0) + 32.0;

    // Arithmetic still works β€” combining with previous section's lessons
    public static Celsius operator +(Celsius left, Celsius right)
        => new Celsius(left.Degrees + right.Degrees);

    public override string ToString() => $"{Degrees:F2}Β°C";
}

// A lightweight struct that ONLY holds Fahrenheit β€” shows cross-type conversion
public readonly struct Fahrenheit
{
    public double Degrees { get; }
    public Fahrenheit(double degrees) => Degrees = degrees;

    // Explicit conversion FROM Celsius TO Fahrenheit
    public static explicit operator Fahrenheit(Celsius c)
        => new Fahrenheit((c.Degrees * 9.0 / 5.0) + 32.0);

    // Explicit conversion back from Fahrenheit to Celsius
    public static explicit operator Celsius(Fahrenheit f)
        => new Celsius((f.Degrees - 32.0) * 5.0 / 9.0);

    public override string ToString() => $"{Degrees:F2}Β°F";
}

class Program
{
    static void Main()
    {
        // Implicit conversion β€” no cast syntax required
        Celsius boiling = 100.0;  // implicit operator Celsius(double) fires here
        Console.WriteLine($"Boiling point: {boiling}");

        // Explicit conversion to double β€” caller must acknowledge scale change
        double boilingF = (double)boiling;
        Console.WriteLine($"In Fahrenheit (as double): {boilingF:F2}");

        // Explicit conversion to Fahrenheit struct
        Fahrenheit boilingFahrenheit = (Fahrenheit)boiling;
        Console.WriteLine($"In Fahrenheit (as struct): {boilingFahrenheit}");

        // Round-trip: Fahrenheit β†’ Celsius β†’ back to Fahrenheit
        var bodyTemp = new Fahrenheit(98.6);
        Celsius bodyTempC = (Celsius)bodyTemp;
        Fahrenheit roundTrip = (Fahrenheit)bodyTempC;
        Console.WriteLine($"Body temp round-trip: {bodyTemp} β†’ {bodyTempC} β†’ {roundTrip}");

        // Arithmetic on Celsius still works naturally
        Celsius morning = 15.0;   // implicit
        Celsius afternoon = 8.0;  // implicit
        Celsius peak = morning + afternoon;
        Console.WriteLine($"Peak: {peak}");
    }
}
β–Ά Output
Boiling point: 100.00Β°C
In Fahrenheit (as double): 212.00
In Fahrenheit (as struct): 212.00Β°F
Body temp round-trip: 98.60Β°F β†’ 37.00Β°C β†’ 98.60Β°F
Peak: 23.00Β°C
⚠ Watch Out:
Implicit conversions can cause hard-to-spot bugs if you're too generous with them. If you make a Celsius-to-Fahrenheit conversion implicit, a method expecting Celsius silently accepts a Fahrenheit value, does the math in the wrong scale, and produces a wrong answer with no compiler warning. Reserve implicit only for conversions where the types are genuinely interchangeable from the caller's perspective.
πŸ“Š Production Insight
A team once defined implicit conversion from string to a CustomerId type. A method overload expecting CustomerId started receiving raw strings from a legacy caller β€” the strings were treated as valid IDs, causing data corruption because the strings were not actually valid customer references.
The silent conversion made the bug nearly impossible to trace. They changed to explicit conversion and added unit tests.
Rule: implicit conversions should only exist when you'd be comfortable removing the type entirely and replacing it with the source type in all public APIs.
🎯 Key Takeaway
Implicit conversion = lossless, safe, and caller never needs to think about it.
Explicit conversion = caller must acknowledge the conversion with a cast.
Overusing implicit conversions leads to silent bugs β€” always prefer explicit unless the conversion is truly identity-preserving.

The true and false Operators β€” Enabling Short-Circuit Evaluation in Custom Types

Most developers never need the true and false operators. They are the gateway to making your type work with && and || in short-circuit evaluation. Without them, you cannot use your custom type in logical expressions the way nullable Booleans do.

The use case is modeling a tri-state Boolean β€” a value that can be true, false, or indeterminate. Libraries like nullable Booleans in databases, or condition models in rule engines, use this pattern. The compiler requires both true and false operators to be defined together. Once you have them, you can use the & and | operators combined with them, and then && and || become available.

Here's how it works: for &&, the compiler evaluates the left operand using the true operator. If it returns true, it evaluates the right operand; otherwise it short-circuits to false. For ||, it uses the false operator similarly. This is how nullable bools like bool? work internally.

Let's implement a simple ThreeState type that supports logical operations.

ThreeStateBoolean.cs Β· CSHARP
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
using System;

// Models a three-state logical value: True, False, Indeterminate
public struct ThreeState
{
    // Internal representation:
    //  1 = True, -1 = False, 0 = Indeterminate
    private readonly sbyte _value;

    private ThreeState(sbyte value) => _value = value;

    public static readonly ThreeState True = new ThreeState(1);
    public static readonly ThreeState False = new ThreeState(-1);
    public static readonly ThreeState Indeterminate = new ThreeState(0);

    // The 'true' operator: returns true if the value is definitely true
    public static bool operator true(ThreeState x) => x._value == 1;

    // The 'false' operator: returns true if the value is definitely false
    public static bool operator false(ThreeState x) => x._value == -1;

    // Logical AND: & operator (needed before && can be used)
    public static ThreeState operator &(ThreeState left, ThreeState right)
    {
        // If either is false, result is false
        if (left._value == -1 || right._value == -1)
            return False;
        // If either is indeterminate, result is indeterminate
        if (left._value == 0 || right._value == 0)
            return Indeterminate;
        // Both are true
        return True;
    }

    // Logical OR: | operator (needed before || can be used)
    public static ThreeState operator |(ThreeState left, ThreeState right)
    {
        // If either is true, result is true
        if (left._value == 1 || right._value == 1)
            return True;
        // If either is indeterminate, result is indeterminate
        if (left._value == 0 || right._value == 0)
            return Indeterminate;
        // Both are false
        return False;
    }

    // Logical NOT: ! operator
    public static ThreeState operator !(ThreeState x)
    {
        return x._value switch
        {
            1 => False,
            -1 => True,
            _ => Indeterminate
        };
    }

    // Override Equals/GetHashCode for consistency
    public override bool Equals(object? obj) => obj is ThreeState other && _value == other._value;
    public override int GetHashCode() => _value.GetHashCode();

    public override string ToString() => _value switch
    {
        1 => "True",
        -1 => "False",
        _ => "Indeterminate"
    };
}

class Program
{
    static void Main()
    {
        var t = ThreeState.True;
        var f = ThreeState.False;
        var i = ThreeState.Indeterminate;

        // Short-circuit && works because true/false operators are defined
        // The compiler generates: if (t) then evaluate f else false
        Console.WriteLine($"t && f: {t && f}");  // False
        Console.WriteLine($"f && t: {f && t}");  // False (short-circuits, no evaluation of right)
        Console.WriteLine($"t || f: {t || f}");  // True (short-circuits, no evaluation of right)
        Console.WriteLine($"f || t: {f || t}");  // True
        Console.WriteLine($"i && t: {i && t}");  // ? (Indeterminate, because i is not true nor false)
        // For i && t: false operator on i returns false (i is not definitely false), so conditional evaluates right side.
        // i && t resolves to i & t = Indeterminate & True = Indeterminate
        Console.WriteLine($"!t: {!t}");
    }
}
β–Ά Output
t && f: False
f && t: False
t || f: True
f || t: True
i && t: Indeterminate
!t: False
Mental Model
Mental Model: Short-Circuit Operators and true/false
The true and false operators are like asking 'is this value definitely true?' and 'is this value definitely false?' respectively.
  • For a type to support &&, it must define & and both true/false operators.
  • For ||, define | and the same true/false operators.
  • The compiler uses the true operator to decide whether to short-circuit in && (if left is not true, skip right).
  • Use this pattern for nullable, tri-state, or fuzzy logic types.
πŸ“Š Production Insight
A rule engine defined a custom ConditionResult type with true/false operators for short-circuit evaluation of complex business rules.
During a deployment, a bug in the true operator caused && to always evaluate both sides, effectively disabling short-circuit logic for 30% of rules.
The latency of rule evaluation increased by 200ms per transaction as a result.
Fix: unit test the short-circuit behavior explicitly by passing a condition that has a side effect (like counting evaluations) and verify only the necessary side effects occur.
🎯 Key Takeaway
true and false operators enable your type to participate in short-circuit && and ||.
Define & and | along with true/false as a pair.
Without them, you can only use & and | (non-short-circuit).
This is an advanced pattern β€” only use it when tri-state or nullable logic is required.
πŸ—‚ Operator Overloading vs Regular Methods
When to use each approach for custom type behavior
AspectOperator OverloadingRegular Methods
Syntax at call siteprice + tax (natural, concise)price.Add(tax) (verbose, method-flavoured)
DiscoverabilityRelies on docs or IDE hints β€” not obvious a '+' is definedShows up in IntelliSense autocomplete immediately
Best fit forValue types that model a real-world quantity (Money, Vector, Temperature)Operations with side effects, multiple return values, or complex parameters
Compound assignment (+=)Automatically derived once operator+ exists β€” you write nothing extraMust write AddInPlace or similar method manually
InteroperabilityOther CLR languages call op_Addition by name β€” works but uglyUniversally callable from any CLR language using standard syntax
Enforcement of symmetryC# forces you to define == and != together, < and > togetherNo automatic pairing β€” easy to forget the inverse method
Risk of misuseCan create confusing code if semantics don't match the symbolMethod name is always explicit β€” harder to mislead
PerformanceInlined by JIT β€” effectively zero overhead for simple struct operationsSame β€” also inlined for simple cases, no meaningful difference

🎯 Key Takeaways

  • Operator overloading compiles to a static method named op_Addition, op_Equality, etc. β€” it's ordinary method dispatch with no hidden magic or runtime cost.
  • Overloading == forces you to also overload != (compiler error otherwise), and you must override Equals + GetHashCode to stay consistent with LINQ, Dictionary, and HashSet behaviour.
  • Compound assignment operators (+=, -=, *=) are automatically synthesised by the compiler once you define the base operator β€” you never write them yourself, and attempting to do so is a compile error.
  • Use implicit conversions only when the conversion is completely lossless and safe; use explicit when precision is lost, the scale changes, or an exception is possible β€” this keeps callers informed of meaningful type boundaries.
  • Overload operators on readonly structs for correct immutable semantics; avoid mutable classes unless you document the reference replacement behavior explicitly.

⚠ Common Mistakes to Avoid

    βœ•Overloading == without overriding Equals and GetHashCode
    Symptom

    Your == works in simple comparisons, but LINQ's .Contains(), Dictionary lookups, and HashSet deduplication use Equals/GetHashCode internally, not your operator. The symptom is a Dictionary not finding a key that you know is there, or a HashSet that contains duplicates.

    Fix

    Always override Equals(object) and GetHashCode() whenever you overload ==, and implement IEquatable<T> so LINQ uses the typed, non-boxing path.

    βœ•Making implicit conversion operators too broad
    Symptom

    You define an implicit conversion from string to your type to avoid cast syntax, and suddenly every method that accepts your type silently accepts raw strings. The symptom is a wrong overload resolving at runtime, or a null string being converted and throwing inside your constructor with a confusing stack trace.

    Fix

    Use implicit only when the source and target types are conceptually the same thing. If there's any doubt, make it explicit.

    βœ•Overloading operators on mutable classes instead of structs
    Symptom

    You overload + on a class, and the operator creates a new instance as expected. But a junior developer on your team writes account += deposit thinking it modifies account in place β€” it actually replaces the reference with a new object, silently discarding any other references to the original object.

    Fix

    Model value types (Money, Vector, Percentage) as readonly struct. The immutability makes operator semantics correct by design β€” operators always return new values, never mutate.

    βœ•Forgetting to implement IEquatable<T> on structs
    Symptom

    Using List.Contains() or Array.IndexOf() on a struct with overloaded == causes boxing and slower performance. The equality check still uses value semantics via the virtual Equals method, but every time the struct is boxed to object, memory allocation occurs.

    Fix

    Implement IEquatable<T> on your struct. The generic interface allows typed calls without boxing.

    βœ•Defining operator+ but not operator- (or vice versa) on a numeric-like type
    Symptom

    Callers expect both addition and subtraction to be available for a numeric type. If only one is defined, the type feels incomplete and forces callers to use makeshift workarounds.

    Fix

    For types that represent numbers or quantities, define all four arithmetic operators (+, -, *, /) if they make sense.

Interview Questions on This Topic

  • QWhy does C# require you to overload == and != together, and what happens if you override Equals without also overriding GetHashCode?Mid-levelReveal
    C# requires overloading == and != together to ensure logical consistency: if two objects are equal, they cannot be unequal. The compiler enforces this pairing. If you override Equals without overriding GetHashCode, two equal objects may hash to different buckets in a hash table, causing lookups to fail even though the key is logically present. You get a compiler warning (CS0659) because the default GetHashCode from Object uses reference equality for classes or field-by-field value hashing for structs, which can differ from your custom equality. Always override GetHashCode using the same fields as Equals, typically via HashCode.Combine.
  • QWhat is the difference between implicit and explicit conversion operators in C#? Give a concrete example of when you'd choose each.SeniorReveal
    Implicit conversion operators allow the compiler to convert from one type to another without any explicit cast, while explicit conversion operators require the developer to write a cast. The key decision is whether the conversion is always safe and lossless. Example: converting a double to a Celsius struct β€” wrapping a double in a struct adds no semantic change, so implicit is fine. Converting Celsius to Fahrenheit changes the scale and introduces a different unit β€” explicit forces the caller to acknowledge the conversion: double f = (double)celsiusTemp;. If you made that implicit, a method expecting Fahrenheit could receive Celsius silently and produce wrong calculations. Reserve implicit for truly identity-preserving conversions.
  • QCan you overload the += operator in C#? How does compound assignment actually work for overloaded types?Mid-levelReveal
    You cannot directly overload += in C# β€” attempting to do so causes a compile error. The C# compiler automatically synthesises compound assignment operators from the corresponding binary operator. For example, if you define operator+, the compiler generates operator+= that calls operator+ and assigns the result back. This ensures that a + b and a += b are always consistent. If you need different behavior for in-place mutation, do not use operator overloading; use a dedicated method like AddInPlace.
  • QExplain how the true and false operators enable short-circuit && and || in C#.SeniorReveal
    The true and false operators are used by the compiler to evaluate short-circuit logical operations. For x && y, the compiler first calls the true operator on x. If it returns true, it evaluates y and applies the & operator. If it returns false (i.e., x is not definitely true), the entire && expression short-circuits to false. For x || y, the compiler uses the false operator: if x is not definitely false, it short-circuits to true; otherwise it evaluates y and applies |. To make this work, you must define both the true and false operators, plus the & and | operators. This pattern is used by nullable bools and tri-state logic types.
  • QWhy is it recommended to overload operators on structs rather than classes?SeniorReveal
    Operators on structs are naturally immutable β€” they return new instances rather than modifying the original. This matches the mathematical semantics of operators: a + b produces a new value. On a class, if you define operator+ to return a new instance, compound assignment a += b silently replaces the reference, which confuses developers who expect in-place mutation (a common mistake). Additionally, value types like Money, Vector, and Temperature are conceptually values, not entities. Using a readonly struct enforces immutability and ensures operator semantics are correct by design. If you must use a class, document the behavior clearly and make the class immutable.

Frequently Asked Questions

Can you overload all operators in C#?

No. C# allows overloading of arithmetic, bitwise, comparison, and unary operators, but deliberately blocks assignment (=), conditional logic (&&, ||), and flow-control operators (new, typeof, is, as). The compound assignment operators like += are also blocked because C# derives them automatically from the base operator, ensuring a + b and a += b are always consistent.

Should I overload operators on a class or a struct in C#?

Prefer struct for types that model a value β€” Money, Vector, Temperature, Percentage. Operators on structs naturally return new values rather than mutating state, which matches how arithmetic operators feel to callers. On a class, operator+ returning a new instance can confuse developers who expect in-place mutation, especially with compound assignment. If your type is inherently reference-based (e.g. a mutable entity with identity), stick to regular methods.

Does overloading == in C# replace the Object.Equals method?

No, and this is a common source of bugs. The == operator and Object.Equals are separate mechanisms. The == operator is a static method resolved at compile time based on the declared type of the variables. Equals is a virtual method resolved at runtime. If you overload == without overriding Equals, types stored in object variables, passed to collections, or compared via LINQ will still use the default reference-equality Equals. Always override both together.

Can I overload the true and false operators for any type?

Yes, but they are rarely needed. They are used to enable short-circuit && and || with your custom type. You must define both true and false operators as a pair, along with the & and | operators. This is an advanced pattern useful for nullable or tri-state logic types. Most business types do not need it.

What happens if I define operator+ but not operator-?

The compiler will not complain β€” it is perfectly valid to define only addition without subtraction. However, callers will expect symmetry for numeric-like types. If your type is meant to represent a quantity, consider defining the full set of arithmetic operators (+, -, *, /) that make sense for the domain. For types where subtraction is not meaningful (e.g., a Temperature struct where subtracting two temperatures gives a temperature difference, not another temperature), you can omit it, but document the decision.

Do implicit conversions cause performance overhead?

Usually not. The compiler inlines conversion methods just like any other method. However, if the conversion is expensive (e.g., involves a database call or complex computation), it will be a hidden cost because the caller does not see a function call. Keep conversions cheap. If the operation is expensive, make it an explicit conversion or a named method so the caller is aware of the cost.

πŸ”₯
Naren Founder & Author

Developer and founder of TheCodeForge. I built this site because I was tired of tutorials that explain what to type without explaining why it works. Every article here is written to make concepts actually click.

← PreviousGenerics in C#Next β†’Indexers in C#
Forged with πŸ”₯ at TheCodeForge.io β€” Where Developers Are Forged