New Language feature in Csharp 3.0 – Extension method

Hi

Another new language feature of the C# 3.0 is the extension method. This feature will also be available on the next version of the VB.Net. Extension methods allow developer to add new methods to a public contract of an existing CLR type without sub classing the type.

Extension Methods help blend the flexibility of "duck typing" support popular within dynamic languages today with the performance and compile-time validation of strongly typed languages.

A simple example of the Extension method would be to add some validation to the string class. Lets say when we want to validate that a string is a valid Email or not we normally use another class with a static method to validate it. The typical example would be

string email = Request.QueryString["email"];

if ( EmailValidator.IsValid(email) ) { }
  

With the help of the new extension methods we can add the IsValisEmail Property to the string class and use it directly on any string variable.

For this we need to add a class like this. The “this” keyword in the parameter will tell the compiler that this is an extension method for the string class. And we will also have the compile time validation and also design time support for the same.

Public static class Extensions
{
    public static bool IsValidEmailAddress(this string s)
    {
        Regex regex = new Regex(“Some regular expression”);
        return regex.IsMatch(s);
    }

}

Now with this in place we can validate the string directly like this

string email = Request.QueryString["email"];

if ( email.IsValidEmailAddress() ) { }

[Note: we will need to import the namespace with the help of the using keyword at the top.]

Thanks
Vikram


Share this post   Email it |  digg it! |  reddit! |  bookmark it!

Feedback

Posted on 3/31/2007 3:02:57 AM

I'd have appreciated if u had come up with an original example, rather than taking it from Scott Guthrie's blog. Scott's blog is most famous and most awaited blog in .NET world.

but anyways..

thanks...

Posted on 3/31/2007 8:15:51 PM

Really cool! Thanks for this

Please post your comments:

Name:  
Email (optional): Your email address will not be posted.
URL (optional):
Comments: HTML will be ignored, URLs will be converted to hyperlinks  
Enter the text you see in the box:
 
Copyright © 2006 - 2008 Vikram Lakhotia