skip to content

Extension Members

Extension methods add static helpers that read like instance calls, and C# 14 extension blocks add properties and static members. Interviewers ask how lookup picks them.

on this pageshow

explore

questions

5

In C#, how do you declare an extension method like WordCount on string, and what does the compiler turn text.WordCount() into?

level: juniorimportance: must knowfreq 72%

answer

  1. a static helper in disguise
  2. modifier on the first parameter
  3. top-level, non-generic static class
  4. call rewritten to ClassName.Method(receiver)

basics

~20 s

Declare a static method in a top-level, non-generic static class and put this before its first parameter. The compiler rewrites text.WordCount() into the static call StringExtensions.WordCount(text), and finds it only when that class's namespace is in scope.

solid answer

~40 s

An extension method is an ordinary `static` method whose first parameter carries the `this` modifier, declared in a top-level, non-generic `static` class such as `StringExtensions`. When the compiler meets `text.WordCount()` and `string` has no applicable `WordCount` of its own, it looks through the extension methods in scope and rewrites the call to `StringExtensions.WordCount(text)`: a plain static call with the receiver as the first argument. Nothing is added to `string` itself, so the method sees only the members it could see anyway, and you can still call it in the static form. The class is found only when its namespace is imported with a `using` directive (or the caller sits in that namespace); otherwise the call fails with CS1061.

code

csharp · 18 lines
csharp
#:property PublishAot=false
using System.Reflection;
using Shared.Text;

string title = "  Hello Extension Members  ";
Console.WriteLine(title.WordCount());                 // instance-call syntax
Console.WriteLine(StringExtensions.WordCount(title)); // what the compiler emits
MethodInfo m = typeof(StringExtensions).GetMethod("WordCount")!;
Console.WriteLine(m.IsDefined(typeof(System.Runtime.CompilerServices.ExtensionAttribute)));

namespace Shared.Text
{
    public static class StringExtensions
    {
        public static int WordCount(this string text) =>
            text.Split(' ', StringSplitOptions.RemoveEmptyEntries).Length;
    }
}

go deeper

for a junior

Recall the recipe: a static method, this on the first parameter, inside a top-level non-generic static class, and a using for its namespace at the call site.

for a middle

Explain the rewrite to a static call with the receiver as the first argument, and why that means no access to private members and no overriding.

for a senior

Read CS1061, CS1106 and CS1109 at a glance, and decide when a helper belongs on the type itself instead of in an extension class.

for a principal

Treat extension namespaces as part of a library's public surface: they appear in every importing file, so group and name them so callers opt in deliberately.

## What an extension method is An **extension method** lets you call a static helper with instance-call syntax. You write `title.WordCount()` and it reads as if `string` had a `WordCount` method, but `string` is untouched: no new member is added to the type, no subclass is created, and nothing changes at run time. The feature is entirely a **compile-time rewrite** performed by the C# compiler. The declaration has three ingredients: - a **`static` method**: the extension method itself; - the **`this` modifier on its first parameter**: the parameter's type is the type being extended, and the argument for it is the **receiver** (the expression before the dot); - a **top-level, non-generic `static` class** to hold it, conventionally named after the extended type, such as `StringExtensions`. The rest of the parameter list is ordinary: more parameters, optional parameters, generic type parameters, constraints. The extended type can be a class, a struct, an interface such as `IEnumerable<T>`, or a type parameter `T`, which is how one helper serves every implementation of an interface. ## The declaration rules the compiler enforces The SDK reports each broken rule with its own diagnostic: | Mistake | Diagnostic the compiler prints | |---|---| | Method is not `static` | CS1105: Extension method must be static | | Containing class is not `static`, or is generic | CS1106: Extension method must be defined in a non-generic static class | | Containing class is nested inside another class | CS1109: Extension methods must be defined in a top level static class | | `this` on a parameter other than the first | CS1100: Method has a parameter modifier 'this' which is not on the first parameter | | Namespace of the class is not imported at the call | CS1061: 'string' does not contain a definition for 'WordCount' and no accessible extension method ... could be found | A missing `static` on the method usually also triggers CS0708, because a static class cannot hold instance members. ## What the call compiles to When the compiler binds `title.WordCount()` it works in this order: 1. It looks for an applicable `WordCount` member on `string` itself. Only if none is applicable does extension lookup begin. 2. It collects the extension methods named `WordCount` from the static classes in scope and keeps those whose first parameter accepts a `string`. 3. It runs ordinary overload resolution on that candidate set, treating the receiver as the first argument. 4. It emits a **static call**: exactly the code `StringExtensions.WordCount(title)` would produce. The `this` modifier itself compiles to `System.Runtime.CompilerServices.ExtensionAttribute` on the method and the class, which is how other assemblies recognise the method as an extension. Because the result is a static call, everything that is true of static methods stays true. The method can reach only the members of `string` that are **accessible** to `StringExtensions` (public ones, or internal ones in the same assembly); it cannot read private fields. It is not virtual, so it cannot be overridden. And the static form keeps working, which is useful in tests or when two extensions clash. ## Finding the method: namespaces and using directives An extension method is available only where its containing class is in scope: - code inside the same namespace (or a nested namespace) finds it without a `using`; - code elsewhere needs a `using` directive for that namespace, or a `global using`, which is how a project's implicit usings make common helpers appear everywhere; - `using static Shared.Text.StringExtensions;` imports the extension methods of that one class. This opt-in is deliberate: a library can ship hundreds of extension methods and none of them clutters a caller's member list until the caller imports the namespace. It also means the same call can compile in one file and fail with CS1061 in another. ## Where C# 14 fits C# 14 adds **extension blocks** (`extension(string text) { ... }`), which can also declare extension properties and static extension members. An instance method declared in a block compiles to the same static method a `this` method produces, so callers cannot tell the two forms apart. The `this` form remains fully supported and is still what most existing code uses. ## Mistakes to avoid - Believing the method is attached to the type at run time; it is a static call chosen at compile time. - Expecting access to private state of the extended type. - Declaring the helper in a nested or generic class and being surprised by CS1109 or CS1106. - Forgetting the `using` in a new file and reading CS1061 as "the method was deleted".

  • Can an extension method read the private fields of the type it extends?
    No. It is an ordinary static method in another class, so it can use only the members that class can access: public members, and internal ones when both live in the same assembly. Extension methods add call syntax, not privileges, which is why they do not break encapsulation.
  • Do you always need a using directive to call an extension method?
    No. Code in the same namespace as the static class, or in a namespace nested inside it, finds the method without one. Everywhere else you need a `using` for the namespace, a `global using` (implicit usings are global usings), or `using static` for that one class; otherwise the call fails with CS1061.
  • When is an extension method a better choice than adding an instance method?
    When you do not own the type (a framework type such as `string`, or an interface others implement), or when the helper belongs to one layer of the application and should not live on the shared type. If you own the class and the behaviour belongs to it, an instance method is simpler and cannot be shadowed.

  • An extension method is attached to the type at run time.
  • An extension method can read the extended type's private fields.
  • Any static class can hold extension methods, nested or generic ones included.
  • A public extension method is visible everywhere without importing its namespace.
  • An extension method can override a method the type already has.
open as a page

In C#, when a type has an instance method and an imported extension method shares its name, which one does a call bind to, and why?

level: middleimportance: must knowfreq 58%

basics

~20 s

An applicable instance method always wins, even when the extension's parameters match better: the compiler searches extensions only when instance lookup finds nothing applicable. The choice is fixed when the caller compiles, so an extension never overrides.

open as a page

In C#, why does calling a string extension method such as IsNullOrBlank on a null reference not throw NullReferenceException at the call?

level: middleimportance: should knowfreq 45%

basics

~20 s

An extension call compiles to a static call that passes the receiver as an ordinary argument, so a null receiver simply arrives as null. Nothing throws at the call; the method body decides whether to accept null or throw.

open as a page

After a C# file imports a second namespace that also defines ToSlug(this string), the build fails with CS0121; how does extension lookup by namespace scope explain it, and how do you fix it?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Extension lookup searches namespace scopes innermost first and stops at the first with applicable candidates, so two equally good ToSlug methods imported at one level give CS0121. Fix it with a static call, an inner-scope using, or one fewer using.

open as a page

In C# 14, how does an extension block add an IsEmpty property and a static member to IEnumerable<T>, and how does it relate to classic extension methods?

level: seniorimportance: nice to knowfreq 25%

basics

~20 s

C# 14 lets a static class declare extension(IEnumerable<T> source) { ... } blocks holding extension properties, methods, operators and static members. They compile to static methods, and an instance method in a block matches a classic this method exactly.

open as a page