TechBubbles Microsoft Technology BLOG

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.

About the author

Kalyan Bandarupalli

My name is kalyan, I am a software architect and builds the applications using Microsoft .NET technologies. Here I am trying to share what I feel and what I think with whoever comes along wandering to Internet home of mine.I hope that this page and its contents will speak for me and that is the reason I am not going to say anything specially about my self here.

2 Comments

  • 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.

TechBubbles Microsoft Technology BLOG

Follow me

Archives

Tag Cloud