C# Language Extension methods on Interfaces


Example

One useful feature of extension methods is that you can create common methods for an interface. Normally an interface cannot have shared implementations, but with extension methods they can.

public interface IVehicle
{
    int MilesDriven { get; set; }
}

public static class Extensions
{
    public static int FeetDriven(this IVehicle vehicle)
    {
        return vehicle.MilesDriven * 5028;
    }
}

In this example, the method FeetDriven can be used on any IVehicle. This logic in this method would apply to all IVehicles, so it can be done this way so that there doesn't have to be a FeetDriven in the IVehicle definition which would be implemented the same way for all children.