Designing Good Extensions
Apply best practices and avoid pitfalls.
Designing Extensions People Love
Extension methods are powerful, but power invites misuse. Good extensions feel like a natural part of the type, are easy to discover, and never surprise the caller. This lesson covers practical guidelines.
Extend Behavior, Not Identity
Prefer extensions for utility behaviors that read well in a pipeline. If a method truly belongs to a type you own, make it a real member instead.
using System;
public static class TimeExtensions
{
// A pleasant, focused helper
public static bool IsWeekend(this DayOfWeek day)
=> day == DayOfWeek.Saturday || day == DayOfWeek.Sunday;
}
public class Program
{
public static void Main()
{
Console.WriteLine(DayOfWeek.Sunday.IsWeekend());
Console.WriteLine(DayOfWeek.Monday.IsWeekend());
}
}All lessons in this course
- Defining Extension Methods
- Extending Interfaces and Generics
- Extension Method Resolution
- Designing Good Extensions