SkillPilotAI

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

C#
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(' ', '-');}
Output
$ dotnet run Helper.csmixer-grinder

26.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.
C#
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(' ', '-');}
Output
$ dotnet run Slug.csmixer-grinder
How an extension call is resolved
  1. 1.s.ToSlug(): does the type have its own instance method ToSlug? If yes, it is called

  2. 2.If not, search static classes in namespaces imported with using

  3. 3.Rewrite the call as TextExtensions.ToSlug(s)

  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.
C#
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(' ', '-');    }}
Output
$ dotnet run Blocks.csTruesteel-bottle
C#
Console.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);    }}
Output
$ dotnet run Gst.cs0.181180.00

26.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.
C#
string? coupon = null;Console.WriteLine(coupon.IsBlank()); static class TextExtensions{    public static bool IsBlank(this string? s)        => string.IsNullOrWhiteSpace(s);}
Output
$ dotnet run NullCheck.csTrue

26.6 Operator overloading: same amount, == False

C#
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;}
Output
$ dotnet run MoneyBug.csFalseFalse

Step 1: implement IEquatable<Money>, override Equals(object?) and GetHashCode, all based on Amount.

C#
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();}
Output
$ dotnet run MoneyEquals.csTrue False

Step 2: operators are always public static; == and != must be defined as a pair.

C#
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}";
Output
$ 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.
Value equality for a class
  1. 1.Default class ==: compares references, False for two new(499)

  2. 2.Implement IEquatable<Money>.Equals on Amount

  3. 3.Override Equals(object?) and GetHashCode from Amount

  4. 4.Define == and != as a pair calling Equals

  5. 5.==, Equals, List.Contains and HashSet all agree

Only need value equality? A record generates all of this

26.7 Indexer: cart[sku]

C#
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;    }}
Output
$ dotnet run Cart.cs30

26.8 Comparison: helper vs extension vs C# 14 block

PointStatic helperthis extension methodC# 14 extension block
Call styleTextHelper.Clean(s)s.Clean()s.Clean(), s.IsBlank
Chaining / IntelliSenseNoYesYes
PropertiesNoNoYes
Static members on the typeNoNoYes (decimal.Gst)
Under the hoodStatic callStatic callStatic 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

  1. Use extension methods for types you do not control.
  2. In new code you can use C# 14 extension blocks.
  3. When you overload ==, also write !=, Equals and GetHashCode.
  4. Create operators only when their meaning is obvious.
  5. 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.