Jason Meridth

I am a continuously learning senior full stack SDE/SRE trying to not let best be the enemy of better.

Buy me a coffeeBuy me a coffee

Orcas - Extension Methods

23 Mar 2007 » »

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;