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;
}
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 infun String.wordCount(), and Swift puts the methods in anextension Stringblock. - 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
| Language | Verdict | Note |
|---|---|---|
| Python | Absent | |
| C++ | Absent | A 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. |
| Java | Absent | |
| C | Does not apply | C has no methods; every function is a free function. |
| C# | Native | |
| JavaScript | Absent | A 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. |
| TypeScript | Absent | As 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. |
| Go | Absent | |
| Rust | Idiom | |
| Kotlin | Native | Extension 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. |
| SQL | Does not apply | A user-defined function takes a value as an argument; SQL has no method syntax. |
| Bash | Does not apply | Bash has no types or methods. |
| PowerShell | Native | Update-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. |
| HTML | Does not apply | HTML has no types or methods. |
| CSS | Does not apply | CSS has no types or methods. |
| Regular expressions | Does not apply | A 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
strorVec<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.
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())
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
stris immutable, so the assignment fails. A subclass such asTextadds the method and keeps the methods ofstr, but only for values made asText.
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());
}
}
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
defaultmethod 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();
}
3 False True
2 2
- Verdict: native. C# 14 added
extensionblocks, which can hold extension methods and extension properties for one receiver.IsBlankis a property, so code writess.IsBlankwith no parentheses. SecondLargestuses the older form, withthison the first parameter, and it works for everyIEnumerable<T>. Both forms compile to static methods, soTextExtensions.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"))))
}
3 3 OK
- Verdict: absent. A method must be declared in the package of its receiver type, so code cannot add a method to
stringor to a type from another package. - A plain function is the usual answer. A new type such as
Textcan have methods, but aTextis not astring: the code must convert values from one type to the other.
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
}
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.
Variations and related ideas
- 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
defaultmethod 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
}
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 thatWordCountis part ofstring. 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
stringorobjectshow 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
- Extension members, C# programming guide, Introduction; Declare extension members; Binding extension members at compile time
- Extensions, Kotlin documentation, Introduction; Extension or member functions?
- Extensions, The Swift Programming Language, Introduction
- Defining Shared Behavior with Traits, The Rust Programming Language, Implementing a Trait on a Type
- Extension method, Wikipedia, Introduction; Support in programming languages
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag QH79DF Edit this page History Report an error Markdown