Extension methods
Extension methods enable adding new methods to existing types (including sealed types or types from external libraries) without modifying their original source code or creating a derived class. They are static methods defined in a static class, with the first parameter marked with the this keyword, indicating the type being extended.
In code
Line 1 is the static class. Line 4 is the extension method: it is static, and its first parameter carries this, so it extends string. The commented usage on line 12 then calls it on a string as if string had always had ToTitleCase.
public static class StringExtensions{ // 'this string str' indicates that ToTitleCase is an extension method for the string type public static string ToTitleCase(this string str) { if (string.IsNullOrEmpty(str)) return str; return System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str.ToLower()); }}// Usage:// string name = "john doe";// string titleCaseName = name.ToTitleCase(); // "John Doe"The Standard Query Operators in LINQ are a prime example of extension methods, extending IEnumerable<T>.
You have been using them
Where isn’t a method on List<T>. It’s an extension method, defined in System.Linq, that extends IEnumerable<T>. That is the whole reason LINQ works on arrays, lists, dictionaries and anything else that implements IEnumerable<T>, without those types having Where or Select built in. It’s the same this trick.
public static IEnumerable<T> Where<T>(this IEnumerable<T> source, Func<T, bool> predicate){ foreach (var item in source) if (predicate(item)) yield return item;}What you can extend, the trap with structs, and why the using matters are in extension methods in practiceExtension methods: custom types, value types and usingWhich types can be extended, how structs behave, and when an extension method is visible.Opens in a new tab.
Where it matters
Extension methods provide a powerful way to augment existing types with new functionality in a clean and non-intrusive manner. They are heavily used by LINQ to provide its fluent query syntax, and they are useful for creating utility methods that feel like part of the original type.
Sources
- Understanding Delegates in C#, ScholarHat · accessed May 16, 2025
- Write LINQ queries, C#, Microsoft Learn · accessed May 16, 2025