Monday, October 15, 2012

C#: Extension Methods


Introduction:
Recently I got a chance of working on extension methods and explored some of the use cases of same.  Extension methods were introduced in C# 3.0

Extension methods allow us to add functionality to existing types without modifying them.  We can add functionality to inbuilt type (string) or any custom type. Extension methods are static and should be placed in static class. Although extension methods are static but they are called as an instance method.

Example:
Following is the example of an Extension method counting number of uppercase letters in a string.
namespace Blog
{
    public static class Extension
    {
public static int CountUpper(this string str)      
{
            int intCount = 0;

            for (int index = 0; index < str.Length; index++)
            {
                    if (char.IsUpper(str[index]))
                   {
                          intCount++;
                   }
            }
            return charcount.Count();
}
     }
}

Here is the calling of this extension method:
string s = "Hello Extension";
int i = s. CountUpper();

After compilation it will be as follows:

Extension. CountUpper(s);


Facts and Rules:
1.  First parameter is preceded by this
2.  First parameter defines the type on which extension method can be called.
3.  Extension method must be public and static.
4.  Class having extension method must also be static.
5.  Namespace Blog needs to be imported to access the extension method.
6.  At compile time, all extension methods are translated into static methods.

Chaining
We can chain extension methods as well.

namespace Blog
{
    public static class Extension
    {
public static int Action1(this string str) {….}    
public static int Action2(this string str) {….}
    }
}

These can be called as follows:
s. Action1().Action2();
OR
s. Action2().Action3();

Most commonly used extension methods are LINQ queries which are developed on existing type.

Extension method vs Instance methods:
We can use extension method to extend the functionality of a type but cannot override existing functionality. If extension method has same name as instance method then extension method will never be called.

    public static class Extension
    {
public static int IndexOf(this string str) {….}    
    }

IndexOf extension method will never be called as string class already has an inbuilt IndexOf method. Although we cannot have extension method with same name as type’s existing method but can overload extension methods to provide new functionality.

No comments:

Post a Comment