VS 2008-Extension Methods

Extension Methods allows developers to add new methods for an existing CLR type. In simple terms it allows developers to add their own methods without having it to added in class and then calling it using the class object. There are many possible scenarios where such methods are useful.

For console applications, the class System.console takes input type as String only. But a user may not write a value and press enter. Since even space/null is taken as string value, program needs to check for valid string. Console application do not have method called IsNullOrEmpty() for Strings. So one possible solution is we can use simple extension methods.

Simple Extension Method Example:

namespace TestExtensionMethods

{

class Test

{
static void Main(string[] args)
{
Console.WriteLine(“Enter a String”);
String s=Console.ReadLine() ;
if (s.IsNullOrEmpty())
{
Console.WriteLine(“Enter a String to Continue”);
Console.ReadLine();
}

}
}

public static class Extensions
{
public static bool IsNullOrEmpty(this string s)
{

return (s == null || s.Trim().Length == 0);
}
}

}

The “this” keyword in the argument of our extension method tells the compiler to add this particular extension method to object of type String. So when i hint “.” keyword on my string variable, my extension variable will show up in the intellisense drop down list .

ramtest.jpg

The extension methods need to be static methods in static class within a namespace that is in the scope as shown above in code.

When to use Them
We must only convert the most reusable code into extension method, so that it provides greater flexibility in handling code and improved readability. Extension methods can be used for any data type where reusablity of methods exists.

2 Responses to “VS 2008-Extension Methods”

  1. Ramaiah Says:

    hmmm …. ll be useful for future reference …
    nice work buddy

  2. gaurav Says:

    good techie stuff yaar….good..hope to see more

Leave a Reply