ZetCode

C# extension method

last modified November 6, 2026

In this article we show how to define and use extension methods in C#.

C# extension method

Extension methods are methods that can be added to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.

Extension methods are static methods defined in a static class, but they are called as if they were instance methods of the extended type. Their first parameter has the this modifier; it specifies the extended type.

Extension methods are only in scope when we import their namespace into our source code with a using directive.

In the standard library, we can find plenty of extension methods, most notably in LINQ. C# 14 added extension blocks, which can also define extension properties and static extension members.

C# LINQ extension methods

LINQ is a set of query capabilities built into C#. Most of its operators are extension methods of IEnumerable<T>.

Program.cs
string[] words = [ "falcon", "oak", "sky", "cloud", "tree", "tea", "water" ];

Console.WriteLine(words.First(word => word.Length == 3));
Console.WriteLine(words.Last(word => word.Length == 3));

Console.WriteLine(Enumerable.First(words, word => word.Length == 5));

The example prints the first and the last word that has three letters.

Console.WriteLine(words.First(word => word.Length == 3));
Console.WriteLine(words.Last(word => word.Length == 3));

Both First and Last are extension methods defined in the Enumerable class of the System.Linq namespace. The namespace is imported implicitly in modern projects.

Console.WriteLine(Enumerable.First(words, word => word.Length == 5));

An extension method is an ordinary static method. The compiler translates words.First(...) into this static call.

$ dotnet run
oak
tea
cloud

C# extension method example

In the following example, we add a new method to the string type.

Program.cs
var msg = "We walked for hours. We saw four hawks in the sky.";

int n = msg.WordCount();
Console.WriteLine(n);

Console.WriteLine("What a day!".WordCount());

public static class StringExtensions
{
    public static int WordCount(this string str)
    {
        return str.Split([' ', '.', '?', '!'],
            StringSplitOptions.RemoveEmptyEntries).Length;
    }
}

The WordCount method is a static method defined in a static class. Its parameter contains the this keyword.

public static int WordCount(this string str)

The this string str parameter makes the method available on all strings. Inside the method, str refers to the string on which the method was called.

int n = msg.WordCount();

The method is called directly on the string.

$ dotnet run
11
3

C# extending int

In the next example, we add extension methods to the int type.

Program.cs
int x = 20;
int y = -5;

Console.WriteLine(x.IsEven());
Console.WriteLine(y.IsEven());

Console.WriteLine(y.Clamp(0, 10));
Console.WriteLine(x.Clamp(0, 10));

3.Times(i => Console.WriteLine($"iteration {i}"));

public static class IntExtensions
{
    public static bool IsEven(this int val) => val % 2 == 0;

    public static int Clamp(this int val, int min, int max) => Math.Clamp(val, min, max);

    public static void Times(this int count, Action<int> action)
    {
        for (int i = 1; i <= count; i++)
        {
            action(i);
        }
    }
}

We add the IsEven, Clamp, and Times methods.

public static int Clamp(this int val, int min, int max) => Math.Clamp(val, min, max);

Additional parameters follow the this parameter. The method delegates to the built-in Math.Clamp.

3.Times(i => Console.WriteLine($"iteration {i}"));

Extension methods can be called on literals too. The Times method runs the given action three times.

$ dotnet run
True
False
0
10
iteration 1
iteration 2
iteration 3

C# extension methods and namespaces

Extension methods are usually placed in a separate namespace. The caller must import the namespace to use them.

Program.cs
using Utils.Text;

var title = "an old falcon in the sky";
Console.WriteLine(title.ToTitleCase());

namespace Utils.Text
{
    public static class TextExtensions
    {
        public static string ToTitleCase(this string s) =>
            string.Join(' ', s.Split(' ').Select(w => w.Length == 0 ? w :
                char.ToUpperInvariant(w[0]) + w[1..]));
    }
}

The ToTitleCase method is defined in the Utils.Text namespace.

using Utils.Text;

Without this directive, the ToTitleCase call would not compile. This keeps extension methods from cluttering types unless they are wanted.

$ dotnet run
An Old Falcon In The Sky

C# generic extension methods

Extension methods can be generic. Extending IEnumerable<T> makes the methods available on all sequences, just like LINQ.

Program.cs
List<int> vals = [-3, -2, -1, 0, 1, 2, 3, 4];

var filtered = vals.WhereAll(e => e > 0, e => e % 2 == 0);
Console.WriteLine(string.Join(", ", filtered));

List<string> words = ["sky", "wrath", "wet", "sun", "pick", "who",
    "cloud", "war", "water", "jump", "ocean"];

var filtered2 = words.WhereAll(e => e.StartsWith('w'), e => e.Length == 3);
Console.WriteLine(string.Join(", ", filtered2));

Console.WriteLine(string.Join(", ", words.Every(3)));

public static class EnumerableExtensions
{
    public static IEnumerable<T> WhereAll<T>(this IEnumerable<T> source,
        params Func<T, bool>[] predicates)
    {
        foreach (T e in source)
        {
            if (predicates.All(p => p(e)))
            {
                yield return e;
            }
        }
    }

    public static IEnumerable<T> Every<T>(this IEnumerable<T> source, int step)
    {
        ArgumentOutOfRangeException.ThrowIfNegativeOrZero(step);
        return source.Where((_, idx) => idx % step == 0);
    }
}

We define the WhereAll and Every extension methods.

public static IEnumerable<T> WhereAll<T>(this IEnumerable<T> source,
    params Func<T, bool>[] predicates)

The WhereAll method returns the elements that satisfy all the given predicates. The params modifier lets us pass the predicates as separate arguments.

if (predicates.All(p => p(e)))
{
    yield return e;
}

The method is an iterator; like LINQ operators, it is lazy.

var filtered = vals.WhereAll(e => e > 0, e => e % 2 == 0);

From the integer list, we select the positive even values. From the string list, we get all words that start with 'w' and have three letters.

return source.Where((_, idx) => idx % step == 0);

The Every method returns every n-th element. It is built on top of the indexed Where overload.

$ dotnet run
2, 4
wet, who, war
sky, sun, cloud, jump

C# Base64 extension methods

In the following example, we create extension methods for encoding and decoding Base64 data. Base64 is a group of binary-to-text encoding schemes that represent binary data in a text string format.

Program.cs
using System.Text;

string msg = "one \U0001F418 and three \U0001F40B";
string base64 = msg.EncodeBase64();
string msg2 = base64.DecodeBase64();

Console.WriteLine(msg);
Console.WriteLine(base64);
Console.WriteLine(msg2);

static class Base64Extensions
{
    public static string EncodeBase64(this string value)
    {
        byte[] data = Encoding.UTF8.GetBytes(value);
        return Convert.ToBase64String(data);
    }

    public static string DecodeBase64(this string value)
    {
        byte[] data = Convert.FromBase64String(value);
        return Encoding.UTF8.GetString(data);
    }
}

The program creates the EncodeBase64 and DecodeBase64 extension methods.

string msg = "one \U0001F418 and three \U0001F40B";

The message contains two emojis, written as escape sequences. They take four bytes each in UTF-8.

byte[] data = Encoding.UTF8.GetBytes(value);
return Convert.ToBase64String(data);

We convert the string to UTF-8 bytes and encode them with Convert.ToBase64String.

$ dotnet run
one 🐘 and three 🐋
b25lIPCfkJggYW5kIHRocmVlIPCfkIs=
one 🐘 and three 🐋

C# extension method resolution

An extension method can never override an instance method. If the type already has an applicable instance method with the same signature, the compiler calls the instance method. On the other hand, an extension method can be called on a null reference.

Program.cs
var p = new Point(3, 4);
Console.WriteLine(p.Describe());

string? s = null;
Console.WriteLine(s.IsEmpty());
Console.WriteLine("".IsEmpty());
Console.WriteLine("sky".IsEmpty());

record Point(int X, int Y)
{
    public string Describe() => $"instance method: ({X}, {Y})";
}

static class Extensions
{
    public static string Describe(this Point p) => "extension method";

    public static bool IsEmpty(this string? s) => string.IsNullOrEmpty(s);
}

Both the Point record and the Extensions class define a Describe method.

Console.WriteLine(p.Describe());

The instance method wins; the extension method is ignored.

string? s = null;
Console.WriteLine(s.IsEmpty());

Since the extension method is a static method receiving the reference as an argument, calling it on null does not throw a NullReferenceException. The method must handle the null value itself.

$ dotnet run
instance method: (3, 4)
True
True
False

C# 14 extension members

C# 14 introduced extension blocks. Inside an extension block, we can define extension methods, extension properties, and static extension members. The receiver is declared once, for the whole block.

Program.cs
List<int> vals = [4, 8, 15, 16, 23, 42];

Console.WriteLine(vals.IsEmpty);
Console.WriteLine(vals.Mean);
Console.WriteLine(string.Join(", ", vals.Evens()));

List<int> none = List<int>.Empty;
Console.WriteLine(none.IsEmpty);

Console.WriteLine("hello".Shout);

public static class Extensions
{
    extension<T>(IEnumerable<T> source)
    {
        public bool IsEmpty => !source.Any();
    }

    extension(List<int> list)
    {
        public double Mean => list.Count == 0 ? 0 : list.Sum() / (double)list.Count;

        public IEnumerable<int> Evens() => list.Where(e => e % 2 == 0);
    }

    extension<T>(List<T>)
    {
        public static List<T> Empty => [];
    }

    extension(string s)
    {
        public string Shout => s.ToUpperInvariant() + "!";
    }
}

We define several extension blocks in a static class.

extension<T>(IEnumerable<T> source)
{
    public bool IsEmpty => !source.Any();
}

The block declares a generic receiver named source. The IsEmpty extension property is available on all sequences. Before C# 14, only extension methods were possible.

public IEnumerable<int> Evens() => list.Where(e => e % 2 == 0);

Methods in an extension block do not use the this modifier; the receiver comes from the block declaration.

extension<T>(List<T>)
{
    public static List<T> Empty => [];
}

When the receiver has no name, the block can contain only static members. The Empty property is called on the type itself: List<int>.Empty.

$ dotnet run
False
18
4, 8, 16, 42
True
HELLO!

Source

Extension members

In this article we have worked with extension methods in C#.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.