Extending C# Enumerators with Methods

Although I personally find C# enumerators to be atrocious, they still have several advantages over constant integers.  One of these advantages is the ability to extend the object with additional logic.  This is accomplished by binding extension methods at compile time.  Consider this common enumerator as an example:

public enum Month
{
    January,
    February,
    March,
    April,
    May,
    June,
    July,
    August,
    September,
    October,
    November,
    December
}

Now say we want to be able to find out the number of days in a month and be able to produce an abbreviation of the month.  Rather than creating an additional class with helper functions that must be remembered and referenced later on, new methods can be added directly to the enumerator like so:

public static class MonthExt
{
    // assumes no leap year
    private static int[] MonthDayCount = new int[] {
        31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

    public static int DayCount(this Month month)
    {
        return MonthDayCount[(int)month];
    }

    public static string Abbreviation(this Month month)
    {
        return month.ToString().Substring(0, 3);
    }
}

The operant piece of code here is the this preceding the type (the enumerator to be extended) of the first argument in each method.  That’s how the compiler knows which method to bind to which type.  Using it is as simple as can be:

Console.WriteLine(Month.April.DayCount());
Console.WriteLine(Month.April.Abbreviation());

This will first print 30 and then Apr to the console.

This entry was posted in C# and tagged , , . Bookmark the permalink.
  • Delicious
  • Facebook
  • Reddit
  • StumbleUpon
  • Twitter
  • RSS Feed
  • Google
  • Digg

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>