tirsdag den 10. januar 2012

Rediscovering extension methods

Spent so much time in another world lately that I totally had forgotten the enjoyment of Extension Methods.


 public class Holidays  
   {  
     public Holidays (int year)  
     {  
       if(year < 1701)  
         throw new ArgumentOutOfRangeException("Year must be higher than 1701.");  
       this._Year = year;  
     }  
     private int _Year;  
     public int Year  
     {  
       get  
       {  
         return _Year;  
       }  
     }  
     public DateTimeOffset EasterSunday  
     {  
       get  
       {  
         int a = this.Year % 19;  
         int b = Convert.ToInt32(Math.Floor(Convert.ToDouble(this.Year / 100)));  
         int c = this.Year % 100;  
         int d = Convert.ToInt32(Math.Floor(Convert.ToDouble(b / 4)));  
         int e = b % 4;  
         int f = Convert.ToInt32(Math.Floor(Convert.ToDouble((b + 8) / 25)));  
         int g = Convert.ToInt32(Math.Floor(Convert.ToDouble((b - f + 1 ) / 3)));  
         int h = (19 * a + b - d - g + 15) % 30;  
         int i = Convert.ToInt32(Math.Floor(Convert.ToDouble(c / 4)));  
         int k = c % 4;  
         int l = (32 + 2 * e + 2 * i - h - k) % 7;  
         int m = Convert.ToInt32(Math.Floor(Convert.ToDouble((a + 11 * h + 22 * l) / 451)));  
         int n = Convert.ToInt32(Math.Floor(Convert.ToDouble((h + l - 7 * m + 114) / 31))); // The month  
         int p = (h + l - 7 * m + 114) % 31 + 1; // The day  
         DateTime easterday = new DateTime(this.Year,n , p);  
         return new DateTimeOffset(easterday);  
       }  
     }  
     public DateTimeOffset GoodFriday  
     {  
       get  
       {  
         return EasterSunday.AddDays(-2);  
       }  
     }  
     public DateTimeOffset ChristmasEve  
     {  
       get  
       {  
         return new DateTimeOffset(new DateTime(this.Year, 12, 24));  
       }  
     }  
   }  


Use:

 DateTime dato = DateTime.Now;  
 DateTimeOffset easter2012 = dato.GetHolidays().EasterSunday;