Extension methods
a method with this
An extension method is a static method whose first parameter carries the keyword this. It must live in a static class, and once its namespace is in scope the method can be called as if it belonged to the type. Nothing about the type changes; the compiler rewrites the call into a static call:
var title = " the c# course ";
Console.WriteLine(title.Clean().Title());
Console.WriteLine($"length {title.Clean().Length}");
Console.WriteLine($"original [{title}]");
static class TextExtensions
{
public static string Clean(this string text) => text.Trim().ToLowerInvariant();
public static string Title(this string text) => char.ToUpperInvariant(text[0]) + text[1..];
}
dotnet run
The c# course
length 13
original [ the c# course ]
The chain reads left to right because each method returns a string, which the next one extends. The original is unchanged, as the last line shows: Clean returned a new string, and a string is immutable anyway. Both methods are also callable as TextExtensions.Clean(title), which is exactly what the compiler emits.
An extension on a sequence
An extension method may be generic, and its constraint applies to the receiver like any other parameter. This one keeps every other item and is lazy, so it works on an array, a list or another query:
var numbers = new[] { 1, 2, 3, 4, 5, 6 };
Console.WriteLine(string.Join(",", numbers.EveryOther()));
Console.WriteLine($"count {numbers.EveryOther().Count()} of {numbers.Length}");
static class SequenceExtensions
{
public static IEnumerable<T> EveryOther<T>(this IEnumerable<T> source)
{
var index = 0;
foreach (var item in source)
{
if (index++ % 2 == 0)
{
yield return item;
}
}
}
}
dotnet run
1,3,5
count 3 of 6
This is the same shape as the LINQ operators of System.Linq.Enumerable: a static class, a this parameter and an iterator body. The lesson on iterators and yield explains the body, and the two together are how a team adds its own operators to every sequence in the project.
An instance method wins
When a type has a real instance method with the same name and a compatible signature, that method is called and the extension is ignored. The compiler does not warn, so the extension looks dead until someone calls it by its static name:
var box = new Box();
Console.WriteLine(box.Describe());
Console.WriteLine(Ext.Describe(box));
Console.WriteLine($"type {box.GetType().Name}");
class Box
{
public string Describe() => "instance";
}
static class Ext
{
public static string Describe(this Box box) => "extension";
}
dotnet run
instance
extension
type Box
The two lines are the same call written two ways, and they ran different methods. That is the rule to remember when an extension on a type from another library stops working after that library adds the method itself: the call silently moved to the new instance method, and if the behaviour differs, so did the program.
Rules and limits
- The class must be static and non-generic; the method must be static, and the first parameter is the one with this.
- The extension cannot reach private members, cannot be virtual and cannot be overridden: it is a static method that only looks like a member.
- A this parameter may be a value type, an interface or a type parameter with constraints; the receiver is passed by value unless the parameter says this ref or this in.
- An extension method is found through the namespaces in scope, so a using of its namespace is what makes it appear. Two extensions with the same signature in two namespaces both in scope is an ambiguous call, CS0121.
Exercises
- Add a Truncate(this string, int) extension and chain it after Clean.
- Write EveryOther without yield and explain why the result is the same but the memory is not.
- Add an extension to int that returns whether the number is even, and call it on a literal.
- Put two extensions with the same name and signature in two namespaces, import both and read CS0121.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What makes a static method an extension method?
Answer
The this keyword on its first parameter
The this parameter is what lets the compiler call it with dot syntax on the receiver.
-
Where must an extension method live?
Answer
In a static class
A non-static class cannot hold an extension method; CS1106 reports the attempt.
-
What does this program print?
Console.WriteLine(" hi ".Trim().Length);Answer
2
Trim removes the two spaces and the remaining string has two characters.
-
An instance method and an extension have the same name and signature. Which runs?
Answer
The instance method
Instance methods are preferred; the extension is only used when the type has no such member.
-
What does this program print?
var s = "abc"; Console.WriteLine(s.Last()); static class E { public static char Last(this string s) => s[s.Length - 1]; }Answer
c
The extension indexes the last character; a sealed type is no obstacle to an extension.
-
What may an extension method not do?
Answer
Reach the private members of the type
It is an outside static method, so it has the access of any other caller.
-
How is
text.Clean()compiled?Answer
As a static call TextExtensions.Clean(text)
The dot syntax is sugar; the call is to the static method with the receiver as first argument.
-
What does this program print?
Console.WriteLine(Ext.Twice(3)); static class Ext { public static int Twice(this int n) => n * 2; }Answer
6
A value type can be the receiver, and the static call is the same method as 3.Twice().
-
Why does the namespace of an extension method matter?
Answer
The method is only found when its namespace is imported
Extension lookup uses the namespaces in scope, like any other name.
-
Which is a good use of an extension method?
Answer
Adding an operator over a type you do not own
An extension adds behaviour from outside, which is exactly what a foreign type needs.
The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev