Skip to content
Tutorials Center
My learning

Topics

Lesson 67 of 182 ยท Classes and Objects

Extension Methods and Extension Members

Learn C# extension methods - the this parameter, static classes, namespaces and discoverability, how LINQ works, plus C# 14 extension blocks with extension properties and static members.

Sometimes you want to add a method to a type you do not own. You would love to write "hello".IsPalindrome() or numbers.Median(), but string and IEnumerable<int> belong to .NET and you cannot edit them. Extension methods solve that: you write an ordinary static method, mark its first parameter with this, and the compiler lets callers use instance-method syntax. The whole of LINQ (Where, Select, OrderBy...) is built from extension methods on IEnumerable<T>.

This lesson covers the classic syntax, the rules that decide when an extension is found (and when a real method wins), practical examples and pitfalls, and then the big addition in C# 14 on .NET 10: extension blocks, which also allow extension properties and static extension members. You should know static members and classes and methods before you start.

Writing an extension method

Three ingredients: a static class (non-generic, not nested), a static method inside it, and this before the first parameter. The type of that first parameter is the type being extended.

C# Your first extension methods

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

When the compiler sees text.IsPalindrome(), it first looks for an instance method named IsPalindrome on string. Finding none, it searches the static classes that are in scope for an extension method whose first parameter accepts a string, and rewrites the call to StringExtensions.IsPalindrome(text). That is all there is. An extension method has no special access: it cannot see private members, and nothing is added to the type at runtime.

You can also call it the plain static way, StringExtensions.IsPalindrome("level"). That is useful to disambiguate, and it is exactly what the compiler emits.

The rules that matter

  1. Instance methods win. If the type already has a method with a matching signature, the extension is never called. Adding an instance method to a library later can silently change which code runs.
  2. Scope controls visibility. Extensions are found only when their namespace is imported with using (or they are in the current namespace or global namespace). Forgetting a using is the usual reason "the method does not exist". Implicit usings cover System.Linq for you.
  3. The first parameter can be any type: a class, struct, interface, enum, generic type, delegate or even null-able values. Extending an interface or a generic T is very powerful because it works for every implementer.
  4. Receivers can be null. string s = null; s.IsPalindrome() compiles and enters the method with text == null. Extension methods are static calls, so no NullReferenceException is thrown by the call itself, only by what you do with the argument. Guard with ArgumentNullException.ThrowIfNull(text) in public libraries.
  5. Value types: the first argument is passed by value, so a mutating extension on a struct changes a copy. Use this ref / this in forms for structs (not for classes) if you really need that, or return a new value.
C# Extensions on interfaces and generics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Because the receivers are IEnumerable<int> and IEnumerable<T>, the extensions work on arrays, lists and any other sequence. The OrDefault method is called on a null string without any exception: it is a static method, and its parameter is annotated string?.

How LINQ is built

LINQ's Where is declared roughly as public static IEnumerable<T> Where<T>(this IEnumerable<T> source, Func<T, bool> predicate), in the static class System.Linq.Enumerable. Writing your own operator is the same:

C# Writing a LINQ-style operator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The chain reads left to right and mixes your TakeEvery with the standard operators, because they all share the same this IEnumerable<T> shape. The word list filtered to length > 3 is kiwi, banana, plum, apple, and every second one is kiwi and plum. The lazy iterator technique comes from indexers and iterators; the LINQ chapter is a few lessons away (LINQ basics).

Extension methods in the wild: good and bad uses

Good uses

  • Adding helpers to types you do not own (string, DateTime, HttpClient).
  • Fluent configuration APIs, such as services.AddMyFeature() on IServiceCollection in ASP.NET Core.
  • Operators for sequences, parsing helpers, converting between types.
  • Providing implementation for all implementers of an interface without forcing a base class (Default interface methods are the alternative, see abstract classes and interfaces).

Be careful

  • Do not use them to hide important state or side effects. A method that looks like it belongs to string should be about strings.
  • Don't put extension methods on object or an unconstrained T. They then show up in IntelliSense everywhere and pollute the experience.
  • Place extension classes in a clearly named namespace and require an explicit using for opt-in. The convention of putting them in the same namespace as the extended type (like System.Linq on IEnumerable) is for library authors who want automatic discovery, and it makes name conflicts more likely.
  • If your own class can simply have the method, then put it there. Extensions are for what you cannot or should not add to the type.

C# 14: extension blocks

Classic extension methods have limits: only methods (no properties, no indexers, no operators), only instance-style, and the awkward this on a parameter. C# 14 (released with .NET 10) introduces an extension block: you declare the receiver once and then write members as if you were inside the extended type.

C# Extension blocks with methods and properties

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The syntax: inside a non-generic static class, write extension(ReceiverType name) { ... }. The members inside use the receiver parameter name for the instance, and they look like normal members (public bool IsEmpty => ...), but the receiver is not a new parameter on each one. Callers use ordinary syntax: cart.IsEmpty, cart.Total, cart.Largest(). Old-style this methods and new blocks can live in the same static class, and old extensions are fully compatible: existing code keeps working, and you can migrate at your own pace.

Static extension members

Leave the receiver name out and the block extends the type itself, with static members that you call on the type name:

C# Static extension members and generics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Static members need no receiver name: extension(int) lets you write int.FromText(...) as if int had that static method, which was impossible before (you could never add string.Join-like statics). Generic blocks take the type parameters on the block: extension<T>(IEnumerable<T> source). A block can contain both instance-style members (those that use source) and static members; a static member of a generic block is called on the constructed type, as IEnumerable<string>.Repeated("ab", 3) demonstrates. Members that can appear today are methods and properties (instance and static); extension operators, indexers, events and nested types are not supported yet.

Extension blocks need a C# 14 compiler (.NET 10 SDK), which this site's editor uses. A project that targets older language versions must keep the this form. The two forms compile to the same kind of static methods, so a library can offer both.

Rules stay the same

Extension blocks keep the principle of the classic form: they add syntax, not access. Instance members of the type still win, you still need the right using, and extensions cannot touch private state or add instance fields (storing data per object is not possible; the nearest tool is a ConditionalWeakTable, which is an advanced technique). Also remember that an extension property is computed on each access, so keep it cheap.

Choosing between the options

You want to... Use
Add behaviour to your own class A normal member
Add a helper to a type you do not own Extension method (or block member)
Add a computed property or static helper to a foreign type C# 14 extension block
Give every implementer of an interface a method Extension method on the interface (or a default interface method)
Need access to private state Not an extension: change the type or use inheritance/composition

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which is required for a classic extension method?

    Classic extension methods are static methods in a static class whose first parameter is marked with this.
  2. 2. A type has an instance method Print(), and you also write an extension method Print(this MyType t). Which one runs for x.Print()?

    Instance methods always take priority. The extension is only considered when no applicable instance member exists.
  3. 3. What happens when you call an extension method on a null reference?

    Extension methods are static calls, so null is passed as the first argument. Any exception depends on what the method does with it.
  4. 4. What can C# 14 extension blocks do that classic extension methods cannot?

    Blocks allow extension properties and static members. Like classic extensions, they cannot reach private state or add fields.
  5. 5. Why do using System.Linq; and a missing namespace import matter?

    The compiler considers only extension classes from namespaces that are imported or enclosing. A missing using makes the method seem not to exist.

Summary

  • An extension method is a static method in a static class whose first parameter has this; the compiler rewrites x.M() to Class.M(x).
  • Instance members win; extensions need their namespace imported; they cannot access private members and work on null receivers.
  • LINQ is a set of extension methods on IEnumerable<T>, and you can write operators with the same shape.
  • C# 14 extension(Type name) { ... } blocks add extension properties and static members (and generic receivers).
  • Use extensions for types you do not own; put behaviour on your own types directly.

Next: Partial, Nested and Local Types