Skip to content
Author: ytianle

Extension Methods⚓︎

We will use string as an example to explain extension methods, but the concept applies to any type.

What Are Extension Methods?⚓︎

In C#, an extension method lets you add a method-like API (a new method call style) to an existing type without modifying that type or inheriting from it.

Take string as an example, you call it like an instance method:

"hello".Shout();

Basic Rules⚓︎

An extension method must follow these rules:

  • it must be declared in a static class.
  • it must be a static method.
  • its first parameter must use the this modifier.
Which type is extended?

The type of the first parameter (the one with this) is the type being extended. In the example above, string is being extended.

public static class StringExtensions
{
    public static string Shout(this string value)
    {
        return value.ToUpperInvariant() + "!";
    }
}

// Usage
string result = "hello".Shout(); // result is "HELLO!"

Class Design⚓︎

  • internal static class is a common choice when the extension methods are only meant to be used inside the current assembly.
  • public static class is a common choice when the extension methods are part of a reusable library API and should be available to other assemblies.
  • private static is not a typical choice here, because private applies to nested types, not top-level extension method container classes.