Extension methods and operator overloading
Extension methods let you call an outside static method on a type with a dot, as if it were the type's own member, without changing that type. Operator overloading and indexers let your own types use ==, + and [ ] naturally, as long as equality is implemented consistently.
26.1 Why is it used?
- Static helper calls cannot be chained: TextHelper.ToSlug(TextHelper.Clean(name)) reads inside out.
- Helpers are not suggested after typing a dot, so new developers never discover them.
- You cannot add a method to string or other types you do not own.
- For a class, == compares references by default, so two Money objects with the same amount are not equal.
26.2 The problem: a static helper class
string name = " Mixer GRINDER ";string slug = TextHelper.ToSlug( TextHelper.Clean(name));Console.WriteLine(slug); static class TextHelper{ public static string Clean(string s) => s.Trim().ToLower(); public static string ToSlug(string s) => s.Replace(' ', '-');}$ dotnet run Helper.csmixer-grinder26.3 Extension methods
- A static method in a static class whose first parameter has the this keyword.
- Calls chain and read left to right: "...".Clean().ToSlug().
- The compiler rewrites it to the same static call, so the output is identical.
string slug = " Mixer GRINDER " .Clean() .ToSlug();Console.WriteLine(slug); static class TextExtensions{ public static string Clean(this string s) => s.Trim().ToLower(); public static string ToSlug(this string s) => s.Replace(' ', '-');}$ dotnet run Slug.csmixer-grinder- Step 1
1.s.ToSlug(): does the type have its own instance method ToSlug? If yes, it is called
- Step 2
2.If not, search static classes in namespaces imported with using
- Step 3
3.Rewrite the call as TextExtensions.ToSlug(s)
- Step 4
4.At run time a normal static method runs
Extension = a compiler shortcut
26.4 C# 14: extension blocks
- extension(string s) { ... } declares the receiver once; no this in every method.
- Extension properties are now possible (IsBlank).
- extension(decimal) without a receiver name holds static extension members (decimal.Gst).
- Compatible with the older this-parameter extension methods.
Console.WriteLine(" ".IsBlank);Console.WriteLine("steel bottle".ToSlug()); static class TextExtensions{ extension(string s) { public bool IsBlank => string.IsNullOrWhiteSpace(s); public string ToSlug() => s.Trim().Replace(' ', '-'); }}$ dotnet run Blocks.csTruesteel-bottleConsole.WriteLine(decimal.Gst);Console.WriteLine(1000m.WithGst()); static class PriceExtensions{ extension(decimal) { public static decimal Gst => 0.18m; } extension(decimal price) { public decimal WithGst() => price * (1 + decimal.Gst); }}$ dotnet run Gst.cs0.181180.0026.5 Extension on null
- An extension method is really a static method; the receiver is just an argument.
- So calling it on null does not crash; here IsNullOrWhiteSpace handles the null.
string? coupon = null;Console.WriteLine(coupon.IsBlank()); static class TextExtensions{ public static bool IsBlank(this string? s) => string.IsNullOrWhiteSpace(s);}$ dotnet run NullCheck.csTrue26.6 Operator overloading: same amount, == False
Money a = new(499), b = new(499);Console.WriteLine(a == b);Console.WriteLine(a.Equals(b)); class Money(decimal amount){ public decimal Amount { get; } = amount;}$ dotnet run MoneyBug.csFalseFalseStep 1: implement IEquatable<Money>, override Equals(object?) and GetHashCode, all based on Amount.
Money a = new(499), b = new(499);Console.WriteLine($"{a.Equals(b)} {a == b}"); sealed class Money(decimal amount) : IEquatable<Money>{ public decimal Amount { get; } = amount; public bool Equals(Money? other) => other is not null && Amount == other.Amount; public override bool Equals(object? obj) => Equals(obj as Money); public override int GetHashCode() => Amount.GetHashCode();}$ dotnet run MoneyEquals.csTrue FalseStep 2: operators are always public static; == and != must be defined as a pair.
public static bool operator ==( Money? left, Money? right) => Equals(left, right); public static bool operator !=( Money? left, Money? right) => !Equals(left, right); public static Money operator +( Money left, Money right) => new(left.Amount + right.Amount); public override string ToString() => $"Rs {Amount}";$ dotnet run Money.csTrueFalseRs 998True1- == calls the static object.Equals(left, right), which handles nulls and then calls our Equals.
- + returns a new Money (Rs 998); HashSet now treats equal amounts as one item.
- Step 1
1.Default class ==: compares references, False for two new(499)
- Step 2
2.Implement IEquatable<Money>.Equals on Amount
- Step 3
3.Override Equals(object?) and GetHashCode from Amount
- Step 4
4.Define == and != as a pair calling Equals
- Step 5
5.==, Equals, List.Contains and HashSet all agree
Only need value equality? A record generates all of this
26.7 Indexer: cart[sku]
var cart = new Cart();cart["mixer"] = 2;cart["bottle"] = 3;cart["mixer"] += 1;Console.WriteLine(cart["mixer"]);Console.WriteLine(cart["kettle"]);class Cart{ private Dictionary<string, int> qty = []; public int this[string sku] { get => qty.GetValueOrDefault(sku); set => qty[sku] = value; }}$ dotnet run Cart.cs3026.8 Comparison: helper vs extension vs C# 14 block
| Point | Static helper | this extension method | C# 14 extension block |
|---|---|---|---|
| Call style | TextHelper.Clean(s) | s.Clean() | s.Clean(), s.IsBlank |
| Chaining / IntelliSense | No | Yes | Yes |
| Properties | No | No | Yes |
| Static members on the type | No | No | Yes (decimal.Gst) |
| Under the hood | Static call | Static call | Static call |
26.9 Common mistakes
- Overloading == and != without Equals and GetHashCode: warnings CS0660, CS0661; price == cart[0] is True but cart.Contains(price) is False because collections use Equals.
- Fix: the operator calls Equals and both Equals and GetHashCode are overridden, so every check agrees.
- Myth: an extension modifies the class. It does not; it only sees public members.
- If the type later gets an instance method with the same name, that method wins and your extension is silently ignored.
- Creating operators whose meaning is not obvious.
26.10 Rules
- Use extension methods for types you do not control.
- In new code you can use C# 14 extension blocks.
- When you overload ==, also write !=, Equals and GetHashCode.
- Create operators only when their meaning is obvious.
- Need only value equality? Use a record.
26.11 Interview tips
- Extension method: a static method in a static class with this on the first parameter; adds a method to a type without changing it.
- C# 14 extension blocks also add extension properties and static members.
- Instance methods always win over extensions; extensions see only public members.
- With == always override Equals and GetHashCode, and define != as its pair.
- Extensions are static calls, so they can run on a null receiver.