Monday, February 1, 2010

Extension Method

Last Few days I was thinking how Microsoft added new method in existing classes of visual studio. I was surprised because I was creating List<> and I was showing me some LINQ methods, but when I commented “Using System.Linq” line, it was showing me default list methods.

But when is removed comments “Using System.Linq”. Now Visual Studio was showing me some Linq methods in the intelligence window.


Then I started searching on the web about it. I found new exciting feature of framework 3.0, which is “Extension Methods”. You can extend existing classes without inheritance using extension methods. There are some which you should keep in mind while writing extension method.
  1. You cannot override existing method by writing extension method.
  2. If extension method has same name as instance method then it will not called, because the priority of instance method is high. At compile time extension method has low priority.
  3. You can write extension for Properties, data Members and events.
It is very simple to write extension method. Create static class and write static extension method in this class. The “this” keyword in the parameters tells the compiler to add the extension method in the type after “this” keyword. In my example “this string” compiler adds extension method to the string class.

namespace ExtensionTest
{
public static class ExtensionOfString
{
public static bool IsNumber(this string value)
{
Regex expression =
new Regex(@"^[0-9]([\.\,][0-9]*)?$");
return expression.IsMatch(value);
}
}
}
Here is an example to use extension method. Include the namespace and call your extension method like the original method of the instance.



 using ExtensionTest;
. . . . .

string number = "4";
bool isNumber = number.IsNumber();

You can see how easy it is to write extension method in Dot net.

1 comment:

  1. Nice post. We appreciate that. Given that ASP.NET is interested in many years, there are numerous developers that are expert at utilizing it to develop the best of apps. Establishing an application in Dot net training in Chennai with the assistance of this systems fairly cost-effective. The easy energy for this will allow the creators to perform the granted occupation inside the stipulated time period. And this also permits supply of quality products and services in dot net platform.Take a look to my blog Dot Net Training Academy in Chennai

    ReplyDelete