Tuesday, July 28, 2009

Basics of Extension Methods in .Net 3.5

.NET 3.5 Extension methods are a great new way of adding functionality to an existing type – even a type you don’t have the source code to modify that type. Suppose you want to add the word count method in the string class along with the existing methods of the string class. This can be achieved either by inheritance or by the extension methods.
In order to use the extension methods, it should be created in the separate class and name space must be referenced in your code. Extension methods are always created as static methods inside the static class. If you provide an extension method with the same signature as a method already available on the type you’re extending, the extension method is ignored.
public static class MyExtensions
{
public static int WordCount(this String str)
{
return str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length;
}

public static string IntToString(this int str)
{
return str.ToString();
}

}
Note this keyword before the first parameter of the method which indicates the compiler that it is an extension method and should be added to the objects of the type “string”.
In order to use the specific extension methods add the namespace in your coding with the help of the using statement. Extension methods are show up in the intellisense after the”.”

string str = "Hello How are you?";
Response.Write(str.WordCount());

2 comments:

  1. Hey thats good but article is not complete like u forget to tell the use of extension methods & their benifits.

    :) Pradeep Tyagi

    ReplyDelete
  2. yeh sure i ll publish it in next article

    ReplyDelete