Tuesday, April 12, 2016

Extension Methods

Extension method is a new feature introduced by C# 3.0. Extension method enables to add new methods in existing class without making any change in source of main class. Even there is no need to re-compile that class for which you have added extension method. Also without using inheritance. Although if have not the source code of class only dll is there than too you can add extension method.

Features

1. Extension method should be static
2. The class where it is defined it also should be static.
3. You cannot override the existing method using extension method.
4. If there is a method already in the class with same signature and name than extension method will not be called.
5. To define the parameter list of extension method this keyword used as first parameter than class name after then a variable name( any valid variable name).
6. If you will press the dot after the object the extension method will appear by VS intellisense.
7. It is application only for methods. Same concept cannot be applied for fields, properties and events.
8. It is different from only static method they can be called by object.
9. It can be in same namespace where it is using or in different one.
10. The object which is calling extension method it is passed automatically to extension method as parameter.
11. Extension method with parameter: Parameter also can be passed in extension method.

Using Code

Suppose you want to add some extension method in a system defined class. Take String for an example.

using System;

namespace UserDefined
{

public static class UserClass


{


public static String ConvertToTitleCase(this string strInstance)
{

Char[] charArray = new char[] { ' ', '.', '?' };

string[] strNew= strInstance.Split(charArray, StringSplitOptions.RemoveEmptyEntries);

for(int i=0;i
{
strNew[i][0] = strNew[i][0].ToUpper();
}
return strNew;
}
}
}

Here ConverToTitleCase is an extension method that can be used anywhere if this name space is included in your class. Here we have taken the example of string class but it can be with any user defined class.

Now we can use this method as shown below.

using System;

namespace Sample
{

class Program
{

static void Main(string[] args)
{

string userInput = string.Empty;
Console.WriteLine("Please Enter your String");

userInput = Console.ReadLine();
//calling Extension Method ConverToTitleCase()

String Output= userInput. ConverToTitleCase();

Console.WriteLine("Output title case string is :"+Output);

Console.ReadKey();

}
}


}


Drawback:


This is not a good practice to use extension method because of static keyword and static keywords take memory for entire program life.

No comments:

Followers

Link