Author:
Extension Methods⚓︎
We will use
stringas 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:
Basic Rules⚓︎
An extension method must follow these rules:
- it must be declared in a
staticclass. - it must be a
staticmethod. - its first parameter must use the
thismodifier.
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 staticclass is a common choice when the extension methods are only meant to be used inside the current assembly.public staticclass is a common choice when the extension methods are part of a reusable library API and should be available to other assemblies.private staticis not a typical choice here, becauseprivateapplies to nested types, not top-level extension method container classes.