Skip to content

Extension Methods

The Course
•
30 min study

How does every IEnumerable<T> have a Where method when the interface doesn't declare one? Where is an extension method: a static method that you call as if it belonged to the object. You can write your own for any type, including those you can't change.

this on the first parameter

Inside a static class, a static method whose first parameter is marked this can be called with a dot. name.Initials() means exactly TextExtensions.Initials(name). Nothing is added to the string type, and the method can't reach its private members.

A new method on string C#
string name = "ada king lovelace";

Console.WriteLine(name.Initials());
Console.WriteLine(TextExtensions.Initials(name));
Console.WriteLine("".Initials().Length);

static class TextExtensions
{
    public static string Initials(this string text)
    {
        var letters = text.Split(' ', StringSplitOptions.RemoveEmptyEntries).Select(word => char.ToUpper(word[0]));
        return string.Concat(letters);
    }
}
Check your prediction
Text
AKL
AKL
0

Writing your own LINQ

Extension methods on IEnumerable<T>, combined with yield, are how LINQ itself works. Yours can join a chain with the standard ones. A generic constraint limits which types get the method.

A method that fits in a chain C#
int[] numbers = { 1, 2, 3, 4, 5 };

var result = numbers.Where(n => n > 1).EveryOther().Select(n => n * 10);
Console.WriteLine(string.Join(",", result));

Console.WriteLine(new[] { 4, 9, 2 }.MaxOr(0));
Console.WriteLine(new int[0].MaxOr(-1));

static class SequenceExtensions
{
    public static IEnumerable<T> EveryOther<T>(this IEnumerable<T> items)
    {
        bool keep = true;
        foreach (T item in items)
        {
            if (keep)
            {
                yield return item;
            }
            keep = !keep;
        }
    }

    public static T MaxOr<T>(this IEnumerable<T> items, T fallback) where T : IComparable<T>
    {
        T best = fallback;
        bool any = false;
        foreach (T item in items)
        {
            if (!any || item.CompareTo(best) > 0)
            {
                best = item;
                any = true;
            }
        }
        return best;
    }
}
Check your prediction
Text
20,40
9
-1

Null and precedence

Because an extension method is really a static call, it can run on a null value without crashing, unlike an instance method. If a type has its own method with the same name, the type's own method wins, and your extension is silently ignored. Choose names that won't clash.

An extension on a null value C#
#nullable enable

string? missing = null;

Console.WriteLine(missing.IsBlank());
Console.WriteLine("  ".IsBlank());
Console.WriteLine("x".IsBlank());
Console.WriteLine("Mixed".ToUpper());

static class TextExtensions
{
    public static bool IsBlank(this string? text) => string.IsNullOrWhiteSpace(text);

    public static string ToUpper(this string text) => "never called";
}
Check your prediction
Text
True
True
False
MIXED

C# 14 extension blocks

C# 14 adds extension blocks, which group members for one type. They also allow extension properties, which weren't possible before. You'll see both forms in real code. The older form remains fully supported.

An extension property C#
Console.WriteLine("hello".Shout);
Console.WriteLine("hello".Repeat(2));

static class TextExtensions
{
    extension(string text)
    {
        public string Shout => text.ToUpper() + "!";

        public string Repeat(int times) => string.Concat(Enumerable.Repeat(text, times));
    }
}
Check your prediction
Text
HELLO!
hellohello

When to use them

Extensions are good for small helpers on types you don't own, and for LINQ-like steps. They're a poor fit for logic that needs private state, or business rules hidden behind a dot on string. If a method needs your own type's data, make it a normal method on that type. Reports.Ordered in the tracker could be either; it stays a plain static method there because it's only called from one place.

Fix it: Not an extension yet

Shorten is meant to be called as if it were a method of string. Run it and read the error.

Not an extension yet C#
Console.WriteLine("extension methods".Shorten(9));

static class TextExtensions
{
    public static string Shorten(string text, int length) =>
        text.Length <= length ? text : text[..length] + "...";
}
Check your prediction
Text
error CS1061
'string' does not contain a definition for 'Shorten'

Shorten is an ordinary static method, so it can only be called as TextExtensions.Shorten(text, 9). One word turns it into an extension method. Add it.

Fix it

Put this before the first parameter:

C#
Console.WriteLine("extension methods".Shorten(9));

static class TextExtensions
{
    public static string Shorten(this string text, int length) =>
        text.Length <= length ? text : text[..length] + "...";
}
Text
extension...

The other requirement is already met: an extension method must be in a non-nested static class. Leave out static on the class and you get error CS1106 instead.

Your turn

Exercise

A sequence toolkit

Write these in a static class, as extension methods:

  • Total(this IEnumerable<Item> items) sums the Price of each Item.
  • Chunks<T>(this IEnumerable<T> items, int size), like Batches from Day 2, using yield.
  • Truncate(this string text, int length), cutting long text and adding ..., so that "abcdef".Truncate(3) gives abc... and shorter text is returned unchanged.

Print the total of a list of two items, the number of chunks of size 2 from a sequence of 5 numbers, and truncations of abcdef and abc to 3.

When it works, it prints:

Text
7.5
3
abc...
abc
Your workspace C#
var items = new List<Item> { new("Tea", 3m), new("Cake", 4.5m) };
Console.WriteLine(items.Count);

record Item(string Name, decimal Price);
Hint 1: the idea

Each one is an ordinary static method. Marking the first parameter with this is the only difference, so write and test it as usual.

Hint 2: a first step

The class must be static and declared after the top-level statements. Start with Truncate, which needs only text[..length].

Show one solution
C#
var items = new List<Item> { new("Tea", 3m), new("Cake", 4.5m) };

Console.WriteLine(items.Total());
Console.WriteLine(Enumerable.Range(1, 5).Chunks(2).Count());
Console.WriteLine("abcdef".Truncate(3));
Console.WriteLine("abc".Truncate(3));

static class Toolkit
{
    public static decimal Total(this IEnumerable<Item> items) => items.Sum(item => item.Price);

    public static IEnumerable<List<T>> Chunks<T>(this IEnumerable<T> items, int size)
    {
        var chunk = new List<T>();
        foreach (T item in items)
        {
            chunk.Add(item);
            if (chunk.Count == size)
            {
                yield return chunk;
                chunk = new List<T>();
            }
        }
        if (chunk.Count > 0)
        {
            yield return chunk;
        }
    }

    public static string Truncate(this string text, int length)
    {
        return text.Length <= length ? text : text[..length] + "...";
    }
}

record Item(string Name, decimal Price);
Text
7.5
3
abc...
abc

Each method is static in a static class, with this on its first parameter, so it reads like a member of the type it extends. Total extends IEnumerable<Item> rather than List<Item>, so it works on any sequence of items, including a query. Chunks is an iterator, so it stays lazy like the rest of LINQ, and it starts a new list for each chunk, so the caller can keep one safely.

Was this article helpful?

Your response is saved on this device.