Extension methods in C#
What they are - adding methods to a type you can't (or don't want to) modify
Extension methods let you "add" a method to an existing type (even one whose source code you don't have access to, e.g. string or List<T> from .NET), without inheritance or modifying the original class.
public static class StringExtensions
{
// "this" before the first parameter - THAT is what marks it as an extension method
public static bool IsValidEmail(this string input)
{
return !string.IsNullOrWhiteSpace(input) && input.Contains("@");
}
}
string email = "test@example.com";
bool valid = email.IsValidEmail(); // the call LOOKS like an ordinary instance method!
How it works "under the hood" - syntactic sugar
This is key to understanding - email.IsValidEmail() is only syntax, the compiler actually generates a call to a static method:
// To co piszesz:
bool valid = email.IsValidEmail();
// What compiles "under the hood":
bool valid = StringExtensions.IsValidEmail(email);
string doesn't physically change - it doesn't get a new method "inside" its definition. This is only a convenient syntax for calling a static method, where the first parameter becomes the "object" on which you call the method.
Syntax requirements
public static class OrderExtensions // 1. The class MUST be static
{
public static decimal GetDiscountedTotal(this Order order, decimal discountPercent) // 2. The method MUST be static, "this" on the first parameter
{
return order.TotalAmount * (1 - discountPercent / 100);
}
}
- The class containing extension methods must be
static - The method must be
static - The first parameter must have the
thismodifier, indicating the type you are "extending"
The best-known example - ALL of LINQ is extension methods
This is something you may not have noticed, despite using it every day:
public static class Enumerable // fragment prawdziwego kodu .NET (uproszczony)
{
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;
}
public static IEnumerable<TResult> Select<T, TResult>(this IEnumerable<T> source, Func<T, TResult> selector)
{
foreach (var item in source)
yield return selector(item);
}
}
var orders = new List<Order> { /* ... */ };
var expensiveOrderIds = orders.Where(o => o.Total > 1000).Select(o => o.Id); // Where/Select to EXTENSION METHODS!
The whole LINQ library (Where, Select, OrderBy, FirstOrDefault, ToList...) is a set of extension methods on IEnumerable<T> - this is precisely why LINQ "just works" on any collection implementing IEnumerable<T>, even one written by someone else, without modifying its code.
Practical use #1 - "extending" built-in .NET types
public static class DateTimeExtensions
{
public static bool IsWeekend(this DateTime date)
=> date.DayOfWeek == DayOfWeek.Saturday || date.DayOfWeek == DayOfWeek.Sunday;
public static DateTime StartOfMonth(this DateTime date)
=> new DateTime(date.Year, date.Month, 1);
}
if (DateTime.Now.IsWeekend()) { Console.WriteLine("Weekend!"); }
var start = DateTime.Now.StartOfMonth();
You can't inherit from DateTime (it is a struct, as we discussed, which doesn't support inheritance) nor modify its source code (it is a built-in .NET type) - an extension method is the only way to add "your own" methods to such a type.
Practical use #2 - helper methods for interfaces
public interface IOrderRepository
{
Task<Order> GetByIdAsync(int id);
Task<List<Order>> GetAllAsync();
}
public static class OrderRepositoryExtensions
{
// Metoda "wygodna", zbudowana na bazie podstawowych metod interfejsu -
// It does NOT have to be implemented in EVERY class implementing IOrderRepository
public static async Task<bool> ExistsAsync(this IOrderRepository repository, int id)
{
var order = await repository.GetByIdAsync(id);
return order != null;
}
}
IOrderRepository repo = new OrderRepository(context);
bool exists = await repo.ExistsAsync(5); // works for EVERY implementation of IOrderRepository automatically
This is a useful technique - if you want to add a "convenient" method derived from an interface's basic contract, you don't have to add it to the interface itself (which would force an implementation in ALL implementing classes) - an extension method gives it "for free" to all implementations at once.
The limitations of extension methods
1. They don't have access to private/protected members - they work only through the public API of the type they extend:
public static class OrderExtensions
{
public static void Broken(this Order order)
{
// order._internalField; // ❌ error - an extension method has no access to private/protected
}
}
2. Instance methods always have PRIORITY over extension methods - if the class has a "real" method with the same signature, the real one always "wins":
public class Order
{
public string Describe() => "Prawdziwa metoda"; // metoda INSTANCYJNA
}
public static class OrderExtensions
{
public static string Describe(this Order order) => "Extension method"; // ta SAMA nazwa
}
var order = new Order();
order.Describe(); // "Prawdziwa metoda" - metoda instancyjna ZAWSZE wygrywa
3. They require a using of the appropriate namespace to be visible:
using MyApp.Extensions; // you MUST import the namespace that contains OrderExtensions
Summary
Extension methods are static methods in a static class, with the
thismodifier on the first parameter - the compiler translates the callobj.Method()intoStaticClass.Method(obj), giving the impression of adding a new method to the type, without actually modifying its definition. This is the foundation of LINQ (Where,Selectare extension methods onIEnumerable<T>) and a practical way to add "convenient" methods to built-in .NET types or to interfaces, without forcing their implementation on every class implementing that interface.