Swami goes Techie

Here i would share my insights on technologies.

Saturday, October 03, 2009

Extension Methods in .Net

A New Feature of .Net:

As we all know, every release of .Net framework carries with it, a greater list of new features and functionalities which makes coding easier and impressive though. Here in this post i would like to brief about the  feature, popularly known as Extension methods.

Extension Methods:

Earlier when we wanted to add some new features to an existing class, we usually end up creating custom classes and then write custom methods to achieve the desired functionality. Though in many places implementing custom classes is inevitable and unavoidable, there are scenarios where we can avoid them by simple using this new feature called Extension methods.

Short and Simple:

KISS, As one of the famous  mantras of coding -Keep It Short and Simple, extension methods of .Net  does the same. Yes, they are very simple to implement and very clean to use.

For ex..) we are all familiar with the DateTime structure of c# –(Represents an instant in time, typically expressed as a date and time of day). Assume that we have a requirement where, we need to show up date in English(Culture – en-US)at many places in the application. If so, we can create a extension method to the DateTime object and use it as similar to any other method of the  DateTime object.

Implementation:

Rules-

1. Extension methods are to be part of a static class.

2. Extension methods are defined as static methods but are called by using instance method syntax.

3. The first parameter of the method, specifies, on which type the method operates on (in our case its the DateTime type) and the parameter holds this keyword as its successor /modifier.

4. There could be additional parameters provided based on the functionality required for the implementation.

Pseudo code- creating Extension methods

public static class DateFormatter
    {
        public static string ToEnglishDate(this DateTime obj)
        {
            CultureInfo culture = new CultureInfo("en-US");
            return obj.ToString("dd MMMM yyyy", culture);
        }
    }

Pseudo code- calling Extension methods

DateTime time = DateTime.Now;
           Console.WriteLine(time.ToEnglishDate());
           Console.ReadLine();

Note:

Extensions

In the above pseudo code block if you observe carefully, the extension method ToEnglishDate is being added to the DateTime type and is accessed as natively as we access the other methods and properties of the DateTime structure.

I hope this post added some value in introducing a simple but a very impressive feature of .Net framework, so lets start using them extensively and enjoy – Happy Coding.

Labels: ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home