Wednesday, November 13, 2013

Extension Method explained by Scott Guthrie

Extension method is something that I find easy to forget from time to time. Scott Guthrie nicely explains it in his blog back in 2007.  All source code below comes from his blog.

using System;
using System.Text.RegularExpressions;
namespace SGExtensions
{
  public static class ScottGuExtensions
  {
    public static bool IsValidEmailAddress( this string s )
    {
      Regex regex = new Regex( @"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$" );
      return regex.IsMatch( s );
    }
  }
}

The this keyword before the string type argument s tells the compiler that this Extension Method should be added to objects of type string .


The above  Extension Method can be applied as follows.
//namespace containing Extension Method Implementation
using SGExtensions; 
...
string email = Request.QueryString["email"];
if( email.IsValidEmailAddress() )
{
  ...
}

Another example of Extension Method....

using System;
using System.Collections;

namespace SGExtensions
{
  public static class ScottGuExtensions
  {
    public static bool In( this object o, IEnumerable c )
 {
   foreach( object i in c )
   {
     if( i.Equals( o )
  {
    return true;
  }
   }
   return false;
 }
  }
}

In the above example, the first parameter to the Extension Method "this object o" indicates that this Extension Method should be applied to all types that derive from the base System.Object base type. Basically, every object in .NET.


This "In( )" method allows to check to see whether a specific object is included within an IEnumerable sequence passed as an argument to the method. Because all .NET collections and arrays implement the IEnumerable interface, the "In( )" method could be a useful and descriptive method for checking whether any .NET object belongs to any .NET collection or array.


The following example uses the "In( )" method.

using system;
using SGExtensions;
s public class Test1
{
  void Test()s
  {
    string[] values = {"Microsoft", "Apple", "FaceBook"};
 bool isInArray = "Google".In( values ); // false
  }
}


using System;
using SGExtensions;
public partial class TestPage : System.Web.UI.Page
{
  void Page_Load()
  {
    if ( TextBox1.In( form1.Controls ) )
 {
   ...
 }
  }
}


using SGExtensions;
...
int [] values = { 0, 4, 5, 9, 42 };
int testValue = 45;
bool isInArray = testValue.In( values ); // false
bool isInArray2 = 42.In( values );       // true

No comments: