Extension methods on interfaces

This is actually quite straightforward, but something that perhaps you may not have thought about.

On my current project, I have the concept of a “PerishableObject” – an object whose value is only valid between two particular dates. The interface for an IPerishable looks something like this:


public interface IPerishable {
    /// <summary>
    /// Get/Set the date that this component is valid from
    /// </summary>
    DateTime? ValidFrom { get; set; }

    /// <summary>
    /// Get/Set the date that this component is valid until
    /// </summary>
    DateTime? ValidTo { get; set; }
}

Now, logically, I wanted to create a helper method called “IsValidOn”, which could be passed a date, and would return true/false indicating if the component is valid on the supplied date. Obviously, I could define this in the interface, but that would leave me to either implement the method on every object which implements the interface, or to create a common base class which implemented that method, and then force all perishable objects to inherit from this base class. Both of these are not desirable!

Thankfully, extension methods in C# 3.0 provide a perfect solution for this:


/// <summary>
/// Determines if the perishable component is valid on the given reference date
/// </summary>
/// <param name="component">The component to be tested</param>
/// <param name="referenceDate">Reference date to test</param>
/// <returns><c>true</c> if the perishable component is valid on the given reference date</returns>
static internal bool IsValidOn(this IPerishable component, DateTime? referenceDate) {
    if (!referenceDate.HasValue) {
        return true;
    }

    return (!component.ValidFrom.HasValue || component.ValidFrom.Value <= referenceDate)
        && (!component.ValidTo.HasValue || component.ValidTo.Value >= referenceDate);
}

Defining extension methods against an interface is a great way of extending the interface without bulking it up.

Posted in .Net, C# by Gerrod at July 14th, 2008.

2 Responses to “Extension methods on interfaces”

  1. graffic says:

    WTF! inheritance not desirable!

  2. Gerrod says:

    No, I’m a big fan of inheritance; however, in this instance, I didn’t want to define a PerishableBase class and force everything to descend from that (for example, an existing object which already had a parent class, but also implemented the interface).

Leave a Reply