15 Feb 2012

Extension Methods

Extension methods are a special kind of static method.
Listing 7-2. Library Pattern Introduces the IsWeekend Helper Method
   1: public static class DateTimeHelper
   2: {
   3:     using System;
   4:     public static bool IsWeekend(DateTime dateTime)
   5:     {
   6:         switch (dateTime.DayOfWeek)
   7:         {
   8:             case DayOfWeek.Saturday:
   9:             case DayOfWeek.Sunday:
  10:             return true;
  11:             default:
  12:             return false;
  13:         }
  14:     }
  15: }

Listing 7-3. Helper Method Approach to Calling IsWeekend
   1: DateTime importantDate = new DateTime(2012, 5, 7);
   2: if (DateTimeHelper.IsWeekend(importantDate))
   3:     WeekendProcessing();
   4: else
   5:     WeekdayProcessing();

Listing 7-4. Declaring the IsWeekend Extension Method
   1: namespace Lender.Slos.Extensions
   2: {
   3:     using System;
   4:     public static class DateTimeExtensions
   5:     {
   6:         public static bool IsWeekend(this DateTime dateTime)
   7:         {
   8:             switch (dateTime.DayOfWeek)
   9:             {
  10:                 case DayOfWeek.Saturday:
  11:                 case DayOfWeek.Sunday:
  12:                 return true;
  13:                 default:
  14:                 return false;
  15:             }
  16:         }
  17:     }
  18: }

Writing the IsWeekend method as an extension method is shown in Listing 7-4. The only real difference between the helper method in Listing 7-2 and the extension method in List 7-4 is that the method parameter starts with the this keyword. The static keyword is applied in the same way and the logic is identical.

Listing 7-5. Extension Method Approach to Calling IsWeekend
   1: DateTime importantDate = new DateTime(2011, 5, 7);
   2: if (importantDate.IsWeekend())
   3:     WeekendProcessing();
   4: else
   5:     WeekdayProcessing();

In many ways this is remarkable. From the code listing and through Visual Studio IntelliSense, the IsWeekend method appears to be defined within System.DateTime, a .NET type that is defined in another assembly. The extension method approach has the following benefits:
  • Code reuse through a helper method
  • Straightforward and readable code
  • Visual Studio IntelliSense support
  • Code semantics are clear and convenient

No comments: