What are extension methods in C#, and how do they let you add functionality to a type you can't modify?
IntermediateAn extension method lets you add what looks like a new instance method to an existing type without changing that type's source code or creating a subclass -- it's declared as a static method inside a static class, with the first parameter prefixed by the 'this' keyword identifying the type being extended; C# then lets you call it using ordinary dot-notation as if it were a genuine instance method. LINQ itself is built almost entirely from extension methods (Where, Select, OrderBy all extend IEnumerable<T>), and ASP.NET Core uses the same pattern extensively for fluently configuring middleware and services.
public static class StringExtensions {
public static string ToTitleCase(this string input) =>
System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(input);
}
string name = "hello world";
Console.WriteLine(name.ToTitleCase()); // "Hello World" -- called like a normal instance method
Real-world example
A team can't modify the sealed, built-in string class directly, so they add a IsValidEmail() extension method to string, letting every part of the codebase call myString.IsValidEmail() with clean, natural syntax rather than a separate static utility method call.
Design Patterns in C#;Interfaces & Abstract Classes