Extension Method : A New Orcas Feature
Extension methods allow developers to add new methods to the public contract of an existing CLR type, without having to sub-class it or recompile the original 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.
Using the new “extension method” language feature in C# and VB, I can instead add a useful ”IsValidEmailAddress()” method onto the string class itself, which returns whether the string instance is a valid string or not. I can then re-write my code to be cleaner and more descriptive like so:
string email = Request.QueryString["email"];
if ( email.IsValidEmailAddress() ) { }
How did we add this new IsValidEmailAddress() method to the existing string type? We did it by defining a static class with a static method containing our “IsValidEmailAddress” extension method like below:
public static class infovishExtensions
{
public static bool IsValidEmailAddress(this string s)
{
Regex regex = new Regex(@”^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$”);
return regex.IsMatch(s);
}
}
Note how the static method above has a “this” keyword before the first parameter argument of type string. This tells the compiler that this particular Extension Method should be added to objects of type “string”. Within the IsValidEmailAddress() method implementation I can then access all of the public properties/methods/events of the actual string instance that the method is being called on, and return true/false depending on whether it is a valid email or not.
To add this specific Extension Method implementation to string instances within my code, I simply use a standard “using” statement to import the namespace containing the extension method implementation:
using infovish;
The compiler will then correctly resolve the IsValidEmailAddress() method on any string. Just write in like :
if ( email.IsValidEmailAddress(“infovish@infovish.com”) ) { } ………
Read from : http://msdn.microsoft.com/dotnetrocks/
About this entry
You’re currently reading “Extension Method : A New Orcas Feature,” an entry on Welcome to ViSh’s Blogs
- Published:
- March 29, 2007 / 9:19 am
- Category:
- Orcas
- Tags:
Hi ITians ! This is Vish here. Lemme brief myself. I have completed my MCA (Master of Computer Application) in 2005 and now having around 3.5+ years of experience in .NET Technologies. Presently I am working as a Sr. Teal Lead with a growing software company in Ahmedabad.
No comments yet
Jump to comment form | comments rss [?] | trackback uri [?]