Jul 29 2007

Extension Methods

Category: C# 3.0Bil@l @ 14:50

Extension methods are a way to extend the functionality of existing types by defining methods that can be invoked either by using the normal instance method syntax or in a static way. They are
defined in a static class, and each extension method should be a static one. The first parameter for the extension method should be preceeded by "this", which denotes the type being extended.
If there are any requried parameters, they can be placed infront of the first one.  

An example will show you how to extend the string class to add a method to check if a string week day is a valid weekday. For instance, Monday is a valid week day, while Mondy is not a valid week day!

First of all we define the static class that should contain the extension methods:

 public static class MyExtendedMethods
    {
        public static bool IsValidWeekDay(this string s) {
            Regex regEx= new Regex(@"^(Sun|Mon|(T(ues|hurs))|Fri)(day|\.)?$|Wed(\.|nesday)?$|Sat(\.|urday)?$|T((ue?)|(hu?r?))\.?$");
            return regEx.IsMatch(s);
        }
    }

As you can see the extension method should be placed inside a static class. Even the extension method should be designated with static keyword.

The static method, IsValidWeekDay, has no parameters and through the use of "this string s" this means this method will operate on the string class. The method returns a boolean value whether the string it is operating on returns true which means it is a valid weekday or false which means the string operating on is not a valid weekday.

Here is a sampel code on how to use the above extension method.

            string currDay= "Monday";
            if (currDay.IsValidWeekDay())
                Console.Write("{0} is a valid day!", currDay);
            else
                Console.Write("{0} is not a valid day!", currDay);

The above shows how to access the extension method as an instance method, if you want, you can also access this method through the use of static method:

            string currDay= "Monday";
            if (MyExtendedMethods.IsValidWeekDay(currDay))
                Console.Write("{0} is a valid day!", currDay);
            else
                Console.Write("{0} is not a valid day!", currDay);

Hope this helps you!
Rergards

Tags:

Comments are closed