Skip to content

1.14 — Extension Methods

← Roadmap · Section: 1. C# Language Fundamentals Prev: 1.13 Lambdas and closures · Next: 1.15 Nullability

Markers: ⭐ 💻 · Confidence: 🔴 · Last reviewed: —


TL;DR

  • An extension method lets you add a method to a type you do not own — string, int, a NuGet library's class — without changing or inheriting from it.
  • The recipe: a static method, in a static class, with this on the first parameter.
  • It is only syntax. The compiler turns text.Slugify() into StringExtensions.Slugify(text). Nothing is really added to the type.

The concept

Sometimes you want a method on a type you cannot edit. You cannot add Slugify() to string — it is sealed and it belongs to Microsoft.

Your options without extension methods are all a bit ugly:

StringHelper.Slugify(title);          // works, but reads backwards

An extension method lets you write it the natural way:

title.Slugify();                      // reads like it belongs there

Nothing magic happens. The type is not modified. The compiler simply sees title.Slugify(), finds no such method on string, then goes looking for an extension method that fits — and rewrites your call into StringExtensions.Slugify(title).

That is why the first big limitation exists: an extension method can only use the public members of the type. It is outside code, so it has no special access.

LINQ is the most famous example. Where, Select and OrderBy are all extension methods on IEnumerable<T>. That is how Microsoft added them to every collection ever written, including ones that existed before LINQ, without changing a single one of them.


How it works

Three requirements, all mandatory:

  1. The class must be static
  2. The method must be static
  3. The first parameter must have this in front of it
public static class StringExtensions
{
    public static string Slugify(this string value)
    {
        return string.Join('-', value.ToLowerInvariant().Split(' '));
    }
}

Now:

"Hello World Again".Slugify();   // "hello-world-again"

// Which the compiler turns into:
StringExtensions.Slugify("Hello World Again");

Extra parameters come after the this one:

public static string Truncate(this string value, int maxLength)
    => value.Length <= maxLength ? value : value[..maxLength] + "…";

description.Truncate(100);

You must import the namespace

The compiler only finds extension methods whose namespace is in scope. If your extension lives in MyApp.Extensions, any file using it needs using MyApp.Extensions;.

This is the number one cause of "why is my extension method not showing up in IntelliSense". A useful trick is to put widely used extensions in a namespace you already import everywhere, or add a global using so it is available in every file (see 1.26).

Real methods always win

If the type has an actual method with the same name and a matching signature, the real method is used and your extension is silently ignored.

public static class MyExtensions
{
    public static string ToString(this object obj) => "mine";
}

someObject.ToString();   // calls the REAL ToString. Yours never runs.

No warning, no error — it just quietly does not work. There is a good reason for this rule: it means a library adding a new method in a future version cannot be hijacked by someone else's extension. But it does make for a confusing debugging session.

Extensions work on null

This surprises people. Because it is really a static method call, this can be null without throwing:

public static bool IsBlank(this string? value)
    => string.IsNullOrWhiteSpace(value);

string? name = null;
name.IsBlank();   // true — no NullReferenceException!

If this were a real instance method, calling it on null would throw immediately. Since it is a static call with null passed as an argument, it works fine.

This is occasionally useful, but be careful — it violates the reader's expectation that calling a method on null blows up.

Extensions on interfaces

This is the most powerful use, and it is exactly how LINQ works:

public static class EnumerableExtensions
{
    public static IEnumerable<IReadOnlyList<T>> Chunk<T>(
        this IEnumerable<T> source, int size)
    {
        var batch = new List<T>(size);
        foreach (var item in source)
        {
            batch.Add(item);
            if (batch.Count == size)
            {
                yield return batch;
                batch = new List<T>(size);
            }
        }
        if (batch.Count > 0) yield return batch;
    }
}

Write it once against IEnumerable<T>, and it works on every collection type in .NET — arrays, lists, sets, database queries, everything.


Code

The most common real use in ASP.NET Core is tidying up service registration:

public static class ServiceCollectionExtensions
{
    public static IServiceCollection AddOrderModule(
        this IServiceCollection services,
        IConfiguration config)
    {
        services.AddScoped<IOrderRepository, EfOrderRepository>();
        services.AddScoped<IOrderService, OrderService>();
        services.Configure<OrderOptions>(config.GetSection("Orders"));
        return services;                       // return it so calls can chain
    }
}

Which turns a long Program.cs into this:

builder.Services
    .AddOrderModule(builder.Configuration)
    .AddPaymentModule(builder.Configuration)
    .AddNotificationModule(builder.Configuration);

Notice the method returns IServiceCollection. That is what allows the chaining. Every Add... method in ASP.NET Core follows this pattern, and it is worth copying — it keeps Program.cs readable as an application grows, and it keeps each module's registrations next to that module's code.


Interview questions

Q: What is an extension method and how do you write one?

It is a way to add a method to an existing type without modifying it or inheriting from it. You write a static method inside a static class, and put the this keyword on the first parameter — that parameter is the type you are extending. The compiler then lets you call it as though it were an instance method. Behind the scenes nothing is added to the type; the compiler just rewrites value.MyMethod() into MyClass.MyMethod(value).

Q: What are the limitations?

Three main ones. It can only use the public members of the type, because it really is outside code — no access to private fields. If the type has a real method with the same signature, that real method always wins and your extension is silently ignored. And the namespace has to be imported, otherwise the compiler will not find it at all, which is the usual reason someone's extension method does not appear.

Q: Can you call an extension method on a null reference?

Yes, and that surprises people. Because it compiles down to a static method call with the value passed as an ordinary argument, null is a perfectly valid argument. So an extension like IsBlank() can handle a null string without throwing. It is occasionally handy, but worth using carefully, because most readers assume that calling a method on null will throw.

Q: Where do you use them in ASP.NET Core?

Most commonly for grouping service registrations. Rather than 40 lines of services.AddScoped<...> in Program.cs, each module exposes an AddSomethingModule(this IServiceCollection services) extension that returns the collection so calls can chain. LINQ itself is entirely extension methods on IEnumerable<T> and IQueryable<T>, and ASP.NET Core's whole configuration API — UseRouting, UseAuthentication, MapControllers — is built the same way.


Traps ⚠️

  • Forgetting the using. The method exists but the compiler cannot see it. This is the most common problem by far.
  • A real method silently wins. No warning that your extension was ignored.
  • They cannot access private members. If you need that, you need a real method.
  • They cannot be used to implement an interface. A type does not satisfy IFoo just because an extension method supplies the missing member.
  • Do not extend object. It puts your method on absolutely everything, cluttering IntelliSense across the entire codebase.
  • Overusing them hides where the code lives. If a method genuinely belongs on the type and you own the type, put it on the type.
  • Extension methods cannot be virtual or overridden. Resolution happens at compile time based on the declared type, so they do not take part in polymorphism.


Sources