Techbubbles

Extension Methods Feature in C# 3.0

It is one of the new feature introduced in C# 3.0 “As the name implies, extension methods extend existing .NET types with new methods.”

Here i am going to extend the String type to write an extension method.

Example Adding a IsValidEmailAddress method onto an instance of string class:

namespace Extensions

{

class TestProgram

{

     static  void  Main(string[] args)

     {

          string strEmployeeEmail  = “kalyan@techbubbles.com”;

          if (strEmployeeEmail.IsValidEmail() ) // IsValidEmail is extension method

{

 //Do something 

           }

     }

}

 

public static class Extensions

{

   public static bool

     IsValidEmail( this string s )

     {

       // Do something 

       return;

     }

}// this key word in front of the parameter makes this an extension method

}

The extension methods should be static methods in a static class with in same  namespace as shown above. The this keyword in front of the parameter makes an extension method.

Related Posts:

  • Pingback: DotNetKicks.com

  • http://tr3v.net Tr3v

    You can put extension methods in a different namespace to the class that is implementing them.

    As long as you add a “using” statement for your extensions namespace in each class that needs to use it, it will be visible.

%d bloggers like this: