How do you write a generic extension method that works with any collection type, like a custom 'IsEmpty()' check?
Short answer
Add a generic type parameter to the extension method itself (after the static method's name), constrained as needed, and use it in the 'this' parameter's type — this lets a single extension method work across many different concrete generic instantiations.
Advertisement
AModel answer
Add a generic type parameter to the extension method itself (after the static method's name), constrained as needed, and use it in the 'this' parameter's type — this lets a single extension method work across many different concrete generic instantiations.
public static class EnumerableExtensions {
public static bool IsEmpty<T>(this IEnumerable<T> source) => !source.Any();
}
List<int> numbers = new();
bool empty = numbers.IsEmpty(); // true, works for any IEnumerable<T>Real-world example
Adding a convenient .IsEmpty() or .None() check reusable across List<T>, arrays, and any other IEnumerable<T> implementation.
Likely follow-ups
- How does this generic extension method interact with LINQ's own extension methods, which are also generic over IEnumerable<T>?
Related topics