0

Extension methods on interfaces

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

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.

Published in .Net, C#

No Responses to “Extension methods on interfaces”

Leave a Reply