Extension Methods

11 questions found

What are extension methods in C#, and how do they let you add functionality to a type you can't modify?

Intermediate
An 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.

Common follow-ups: Why must the containing class and the extension method both be static?;How does the compiler decide between a genuine instance method and an extension method if both exist with the same name?

Design Patterns in C#;Interfaces & Abstract Classes

Showing 11–11 of 11