Extension methods allow adding new methods to the public contract of an existing CLR type, without having to sub-class it or recompiling the original type. VB also supports extension methods.
A simple example would be to check for valid email address. We would probably create a static function and pass the input string
using System.Text.RegularExpressions;
namespace Master
{
public class GenericFunctions
{
public static boolean IsValidEmail(string strIn)
{
return Regex.IsMatch(strIn, "^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
}
}
}
//Add the reference
using Master.GenericFunctions;
...
string strEmail = Request.QueryString[“email”];
if (!GenericFunctions.IsValidEmail(strEmail))
MessageBox.Show(“Invalid Email Address”)
Now with the help of extension methods, we can do this…
string strEmail = Request.QueryString[“email”];
if (strEmail.IsValidEmail())
MessageBox.Show(“Invalid Email Address”)
By make the following changes in the GenericFunctions class
using System.Text.RegularExpressions;
public static class GenericFunctions
{
public static boolean IsValidEmail(this string strIn)
{
return Regex.IsMatch(strIn, "^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
}
}
The static method 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 IsValidEmail () method, we can 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. Next time we would explore extension methods provided within the System.Linq namespace. Happy journey!
Submitted by Kashif Pervaiz
Thursday, July 24, 2008
Extension Methods in VS 2008 (C#)
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment