0Pricing
C# Academy · Lesson

Extending Interfaces and Generics

Add behavior across many types at once.

Extending Interfaces

You can write an extension method whose this parameter is an interface. Every type that implements the interface instantly gains the method. This is exactly how LINQ adds dozens of methods to IEnumerable<T>.

A Generic Extension on IEnumerable

By making the method generic over T and extending IEnumerable<T>, the helper works for any sequence: lists, arrays, query results, and more.

using System;
using System.Collections.Generic;

public static class EnumerableExtensions
{
    public static bool IsEmpty<T>(this IEnumerable<T> source)
    {
        foreach (var item in source) return false;
        return true;
    }
}

public class Program
{
    public static void Main()
    {
        var nums = new List<int> { 1, 2, 3 };
        Console.WriteLine(nums.IsEmpty());
        Console.WriteLine(new int[0].IsEmpty());
    }
}

All lessons in this course

  1. Defining Extension Methods
  2. Extending Interfaces and Generics
  3. Extension Method Resolution
  4. Designing Good Extensions
← Back to C# Academy