Thursday, January 5, 2012

A few words about C# extension

A few days ago I was digging MDN C# field for something interesting for me.  It was several articles about C# extension methods. It’s quite useful things.
The basic idea is that the set of methods available on an instance of a particular type is open to extension. As result, we can add new methods to existing types.  I thing most of us  already impacted with  some issues such as requirements to extend third party  classes, sealed classes and so on. In such cases, most general way here is create “helper” class or methods and use it everywhere. Sure, it can be.
C# has better solution.
Imagine we are wants to get all Mondays start from selected date.
Piece of cake, check result:





1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DateTimeExtensions;



namespace DateTimeExtensions{
 public static class DateHelper
    {
        public static IEnumerable<DateTime> GetMondays(this DateTime startDate)
        {
            DateTime endDate = new DateTime(startDate.Year, 12, 31);

            while (startDate.DayOfWeek != DayOfWeek.Monday)
                startDate = startDate.AddDays(1);

            while (startDate < endDate)
            {
                yield return startDate;
                startDate = startDate.AddDays(7);
            }
        }
    }
}
namespace UsingExtensions
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime startDate = new DateTime(1983, 7, 23); //
            foreach (DateTime monday in startDate.GetMondays())
                Console.WriteLine(monday.ToString());
               
            Console.ReadKey();
        }      
    }

}





At the end of the end I would like to provide several rules:
couple of rules to consider when deciding on whether or not to use extension methods:

·         Extension methods cannot be used to override existing methods

·         An extension method with the same name and signature as an instance method will not be called

·         The concept of extension methods cannot be applied to fields, properties or events

·         Do not overuse extension methods; it can be a bad thing!

No comments:

Post a Comment