Extension methods on Interfaces

suggest change

An extension method can give every implementer of an interface the same behavior. Before default interface methods, the interface itself could not supply that body.

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

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

FeetDriven is available on every IVehicle. One mile is 5280 feet, and that conversion does not have to be copied into each class.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents