Orcas – Extension Methods

Again, I was reading Guthrie’s blog and found his post on Extension Methods

What this allows a developer to do is extend types without needing to create a static service class.
It is more like an extension class.

Example:

You want to add a method called IsValidEmailAddress to the base string class:

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

if ( email.IsValidEmailAddress() ) {
}

You would create the following (the this keyword in the parameter list is the key)

public static class OrcasExtensions
{
   public static bool IsValidEmailAddress(this string s)
   {
      Regex regex = new Regex(@”^[w-.]+@([w-]+.)+[w-]{2,4}$”);
      return regex.IsMatch(s);
   }
}

Just add the following to your class:

using OrcasExtensions;

Related Articles:

Post Footer automatically generated by Add Post Footer Plugin for wordpress.

About Jason Meridth

Continuously learning software developer trying to not let best be the enemy of better
This entry was posted in .NET. Bookmark the permalink. Follow any comments here with the RSS feed for this post.

Comments are closed.