Tuesday, May 10, 2011

Extension method (.Net 3.5 and above)

Introduction
Extension method is new to C#.Its allow you to add new method to the existing class.
Description
1.Extension method allows you to add new method to the existing class without modifying the code, recompiling or modifying the original code.
2.Extension method are special kind of static method but they are called using instance method syntax. Their first parameter specify which type the method operate on, and the parameter is precede by  “this” modifier.
3.Extension method are only in scope when you explicitly import the namespace into your source code with “using” directive.
For Example in string object there is no method call “Reverse()”  function .But if you need to extend the string ….
Sample Code
C# Code
namespace ExtensionMethods
{
public static class ExtensionsClass
{
public static string Reverse(this String strReverse)
{
char[] charArray = new char[strReverse.Length];
int len = strReverse.Length – 1;
for (int i = 0; i <= len; i++)
{
charArray[i] = strReverse[len-i];
}
return new string(charArray);
}
}
}
C# Code
How to use?
string s = “Hello Extension Methods”;
string strReverse = s.Reverse ();
Here “s” is nothing but the parameter of Reverse() method.
Conclusion
Extension method is nothing but the Visitor pattern.
Visitor Pattern:-
Visitor pattern allows us to change the class structure without changing the actual class. Its way of separating the logic and algorithm from the current data structure. Due to this you can add new logic to the current data structure without altering the structure. Second you can alter the structure without touching the logic

No comments:

Post a Comment