Programming Search⌘K

Conceptcore

Extension methods

Also called extension method, extension function, extension member, extension property, extension block, Swift extension, extension trait.

An extension method is a function declared outside a type that code calls with method syntax, as if it were a member of that type.

Applies to
core-languages

Idea

An extension method is a function that code calls as if it were a method of a type, but that is declared outside the type. It lets code add a method to a type that it cannot change, such as string or a class from a library. The C# guide says: "Extension members enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type."1

The type does not change. The compiler turns the call s.WordCount() into a call of a static function with s as its first argument. In C#:

using System;
using System.Linq;

string s = "Hello Extension Methods";
Console.WriteLine(s.WordCount()); // called like a method of string
Console.WriteLine(TextExtensions.WordCount(s)); // the same static method, called directly
int[] numbers = [10, 45, 15];
Console.WriteLine(string.Join(" ", numbers.OrderBy(n => n))); // LINQ: extension methods on IEnumerable<T>

static class TextExtensions
{
    public static int WordCount(this string text) =>
        text.Split(' ', StringSplitOptions.RemoveEmptyEntries).Length;
}
Output
3
3
10 15 45

this string text makes WordCount an extension method of string, so s.WordCount() and TextExtensions.WordCount(s) are the same call. OrderBy is an extension method too: LINQ adds its query methods to every type that implements IEnumerable<T>.

How it works

  • A static function with a receiver parameter. C# marks the first parameter with this. "Extension methods are static methods, but they're called as if they were instance methods on the extended type."1 Kotlin writes the type before the name, as in fun String.wordCount(), and Swift puts the methods in an extension String block.
  • The type does not change. Kotlin says: "extensions don't modify the classes or interfaces they extend. When you define an extension, you don't add new members."2 An extension method can use only the public members of the type, so it cannot break encapsulation.
  • Scope by import. An extension method is visible only where its namespace, package or trait is imported. In C#, "Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive."1
  • Static binding. The compiler picks the extension method from the declared type of the expression, at compile time. "Extension functions are dispatched statically, meaning the compiler determines which function to call based on the receiver type at compile time."2 An extension method is not virtual, so a subclass cannot override it.
  • Members first. The compiler looks for a member of the type before it looks for an extension. "At compile time, extension members always have lower priority than instance (or static) members defined in the type itself."1

In languages

LanguageVerdictNote
PythonAbsent
C++AbsentA free function that takes the object as a parameter is the usual answer, and argument-dependent lookup finds it, but the call cannot use the dot syntax.
JavaAbsent
CDoes not applyC has no methods; every function is a free function.
C#Native
JavaScriptAbsentA plain function is the usual answer; code can also add a method to a prototype, which changes the type for all code, not only for code that imports it.
TypeScriptAbsentAs JavaScript; declaration merging tells the compiler about a method that code adds to a prototype; no example file because it would repeat the JavaScript answer.
GoAbsent
RustIdiom
KotlinNativeExtension functions and extension properties such as fun String.wordCount(), dispatched statically; no example file because kotlinc is not installed on the machine that recorded the examples.
SQLDoes not applyA user-defined function takes a value as an argument; SQL has no method syntax.
BashDoes not applyBash has no types or methods.
PowerShellNativeUpdate-TypeData with -MemberType ScriptMethod adds a script method to a .NET type for the session; no example file because pwsh is not installed on the machine that recorded the examples.
HTMLDoes not applyHTML has no types or methods.
CSSDoes not applyCSS has no types or methods.
Regular expressionsDoes not applyA pattern has no types or methods.
Language Verdict Mechanism
Python absent a plain function; a subclass; user classes can get new methods at run time (monkey patching)
JavaScript absent a plain function; code can add a method to a prototype, which changes the type for all code
TypeScript absent as JavaScript; declaration merging can add the method to the type
Java absent static methods in a utility class; default methods in interfaces
Kotlin native extension functions and extension properties, fun Type.name()
C# native this on the first parameter of a static method; C# 14 extension blocks with properties and operators
Go absent a plain function, or a new type declared in the package, which can have methods
Rust idiom an extension trait: a local trait implemented for a type from another crate
C n/a no methods
C++ absent free functions found by argument-dependent lookup; no call syntax with a dot
Bash n/a no types or methods
PowerShell native Update-TypeData -MemberType ScriptMethod adds script methods to a .NET type for the session
SQL n/a user-defined functions take a value as an argument; no method syntax
Regex n/a no types or methods
HTML n/a no types or methods
CSS n/a no types or methods
  • Kotlin and Swift make extensions part of the everyday style. Swift extensions "add new functionality to an existing class, structure, enumeration, or protocol type",3 and they can also make a type conform to a protocol. Neither can replace a method: Swift says that extensions "can't override existing functionality."
  • Rust has no extension methods, but a trait does the same job. A crate can define a trait and implement it for str or Vec<T>, because "we can implement a trait on a type only if either the trait or the type, or both, are local to our crate."4 The methods are in scope where the trait is imported.
  • Python, Ruby and JavaScript can change a class at run time, so they need no extension methods. Wikipedia says: "In dynamic languages like Python, the concept of an extension method is unnecessary because classes (excluding built-in classes) can be extended without any special syntax".5 That is monkey patching, and the change is visible to all code, not only to code that imports it.
  • Go does not allow methods on a type from another package. Code declares a new type, such as type Text string, or uses a plain function.
PythonGitHub
def word_count(text):  # a plain function: the usual answer in Python
    return len(text.split())


print(word_count("Hello plain functions"))
try:
    str.word_count = word_count  # a built-in type cannot get new attributes
except TypeError as e:
    print(e)


class Text(str):  # a subclass can add the method
    def word_count(self):
        return len(self.split())


print(Text("one two").word_count(), Text("x").upper())
Output
3
cannot set 'word_count' attribute of immutable type 'str'
2 X
  • Verdict: absent. Python has no extension methods. A plain function is the usual answer, and a user-defined class can get a new method at run time, which is monkey patching.
  • A built-in type such as str is immutable, so the assignment fails. A subclass such as Text adds the method and keeps the methods of str, but only for values made as Text.
JavaGitHub
public class Main {
  static final class Texts { // a utility class: the usual answer in Java
    private Texts() {}

    static int wordCount(String text) {
      String t = text.strip();
      return t.isEmpty() ? 0 : t.split("\\s+").length;
    }
  }

  interface Shape {
    double area();

    default String describe() { // a default method: the author of the interface adds it
      return getClass().getSimpleName() + " " + area();
    }
  }

  record Square(double side) implements Shape {
    public double area() {
      return side * side;
    }
  }

  public static void main(String[] args) {
    System.out.println(Texts.wordCount("Hello static methods"));
    System.out.println(new Square(3).describe());
  }
}
Output
3
Square 9.0
  • Verdict: absent. Java has no extension methods. A static method in a utility class, such as Texts.wordCount(s), is the usual answer, and libraries such as Lombok and Manifold add extension methods with compiler plugins.
  • A default method adds a method to every class that implements an interface, but only the author of the interface can add it, and a class can override it.
using System;
using System.Collections.Generic;
using System.Linq;

string s = "Hello extension members";
Console.WriteLine($"{s.WordCount()} {s.IsBlank} {"  ".IsBlank}");
int[] xs = [3, 1, 2];
Console.WriteLine($"{xs.SecondLargest()} {TextExtensions.WordCount("one two")}");

static class TextExtensions
{
    extension(string text) // an extension block, new in C# 14
    {
        public int WordCount() => text.Split(' ', StringSplitOptions.RemoveEmptyEntries).Length;

        public bool IsBlank => string.IsNullOrWhiteSpace(text); // an extension property
    }

    public static T SecondLargest<T>(this IEnumerable<T> source) => // the older form
        source.OrderDescending().Skip(1).First();
}
Output
3 False True
2 2
  • Verdict: native. C# 14 added extension blocks, which can hold extension methods and extension properties for one receiver. IsBlank is a property, so code writes s.IsBlank with no parentheses.
  • SecondLargest uses the older form, with this on the first parameter, and it works for every IEnumerable<T>. Both forms compile to static methods, so TextExtensions.WordCount("one two") is a valid call too.
package main

import (
	"fmt"
	"strings"
)

// func (s string) WordCount() int { ... } does not compile:
// a method needs a receiver type that is declared in this package.

// WordCount is a plain function: the usual answer in Go.
func WordCount(s string) int { return len(strings.Fields(s)) }

// Text is a new type with string as its underlying type, so it can have methods.
type Text string

func (t Text) WordCount() int { return WordCount(string(t)) }

func main() {
	s := "Hello defined types"
	fmt.Println(WordCount(s), Text(s).WordCount(), strings.ToUpper(string(Text("ok"))))
}
Output
3 3 OK
  • Verdict: absent. A method must be declared in the package of its receiver type, so code cannot add a method to string or to a type from another package.
  • A plain function is the usual answer. A new type such as Text can have methods, but a Text is not a string: the code must convert values from one type to the other.
RustGitHub
trait WordCount {
    fn word_count(&self) -> usize;
}

impl WordCount for str {
    // a local trait, implemented for a type of the standard library
    fn word_count(&self) -> usize {
        self.split_whitespace().count()
    }
}

fn main() {
    let s = "Hello extension traits";
    println!("{} {}", s.word_count(), WordCount::word_count("one two"));
    println!("{}", String::from("a b c").word_count()); // a String derefs to str
}
Output
3 2
3
  • Verdict: idiom. Rust has no extension methods, but a crate can define a trait and implement it for a type from the standard library, such as str. The orphan rule allows this because the trait is local.
  • The method is in scope only where the trait is in scope, which is the same rule as an import of C# extension methods. WordCount::word_count("one two") calls it as a plain function.
  • Extension properties and static extensions. Kotlin has extension properties, and C# 14 added extension blocks: "Extension blocks support multiple member types: methods, properties, and operators."1 A static extension adds a member to the type itself, not to its instances.
  • Fluent interfaces. LINQ, Kotlin's collection functions and Rust iterator adapters let code write a chain such as xs.Where(...).Select(...).OrderBy(...) on any collection, with no change to the collection types.
  • Default methods. A Java default method or a Rust trait method with a body adds a method to every type that implements an interface. The author of the interface adds it, so it can be overridden.
  • Related tasks. Add a method to an existing type compares the ways to get the result in each language, and partial classes split a type that code owns.

Pitfalls

  • No dynamic dispatch, and members win. The compiler picks an extension from the declared type, and it never calls an extension that has the same signature as a member. A C# extension method can also be called on null, because the call is a static call:
using System;

Shape s = new Square();
Console.WriteLine(s.Describe()); // chosen by the declared type, Shape
Console.WriteLine(new Square().Describe()); // chosen by the declared type, Square
Console.WriteLine(new Square().Name()); // a member always wins over an extension
Square? none = null;
Console.WriteLine(none.Describe()); // no NullReferenceException: it is a static call

class Shape
{
}

class Square : Shape
{
    public string Name() => "member Name";
}

static class ShapeExtensions
{
    public static string Describe(this Shape s) => "a shape";

    public static string Describe(this Square? s) => s is null ? "no square" : "a square";

    public static string Name(this Square s) => "extension Name"; // never called
}
Output
a shape
a square
member Name
no square
  • A new member hides an extension. When a later version of a library adds a member with the same name and signature, the compiler calls the member, and the extension method is silently ignored.
  • Name clashes between extensions. Two imported namespaces or traits with extension methods of the same name make the call ambiguous, and the code does not compile until the call names one of them.
  • Hard to find. A reader of s.WordCount() can think that WordCount is part of string. An IDE shows the declaring class, but a reader of plain text cannot see it.
  • Too many extensions. Extensions on a common type such as string or object show in every completion list. Put them in a namespace that only the code that needs them imports.

Cost

An extension method call is a static call, with the receiver as the first argument, so it costs the same as a call of a static method, and the compiler can inline it. It never costs a virtual dispatch. A Rust extension trait method is also called with static dispatch, unless the code calls it through a dyn trait object. Extension methods do not change the size or the layout of the type.

History

Smalltalk let code add a method to any class: "In Smalltalk, any code can add a method to any class at any time".5 Objective-C categories did the same in a compiled language, and Swift extensions are "similar to categories in Objective-C."3 C# 3.0, released in November 2007, had "Extension methods" in its list of major features,6 so that LINQ could add query methods to all collections. Kotlin and Swift made extensions a main part of their style, and C# 14, released in November 2025, added "Extension members" with properties and operators.

References

  1. Extension members, C# programming guide, Introduction; Declare extension members; Binding extension members at compile time
  2. Extensions, Kotlin documentation, Introduction; Extension or member functions?
  3. Extensions, The Swift Programming Language, Introduction
  4. Defining Shared Behavior with Traits, The Rust Programming Language, Implementing a Trait on a Type
  5. Extension method, Wikipedia, Introduction; Support in programming languages
  6. The history of C#, Microsoft Learn, C# version 3.0; C# version 14

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/QH79DF/text.yaml