What is an extension method in C#?
Quick Answer
An extension method is a static method in a static class whose first parameter is marked this SomeType x. It can then be called as if it were an instance method on that type — myString.ToSlug() — without modifying or inheriting the type. All of LINQ (Where, Select) is extension methods on IEnumerable<T>.
An extension method lets me add what looks like an instance method to a type I don't own. It's a static method in a static class with this on the first parameter — public static string ToSlug(this string s) — and then I can call text.ToSlug(). The compiler just rewrites it to the static call. LINQ is the big example: Where and Select are extension methods on IEnumerable<T>. They can't touch private state and an instance method with the same name always wins.
- The compiler rewrites
list.MyExtension(x)toMyExtensions.MyExtension(list, x). - They can't access private members, can't truly override, and instance methods win if there's a name clash.
- Need a
usingfor the namespace of the static class. - Good for: fluent helpers on interfaces you don't own, LINQ-style pipelines, small conveniences on framework types.
- Avoid: hiding important behaviour, extension methods that do a lot of work or hit I/O (surprising for callers), extensions on
object.
public static class StringExtensions
{
public static bool IsNullOrBlank(this string? s)
=> string.IsNullOrWhiteSpace(s);
}
// usage — feels like an instance method
if (name.IsNullOrBlank()) { /* ... */ }