Extension Methods

In my last post I talked about using Lamba expressions. C# 3.0 includes extension methods.

 

List<Person> people = new List<Person>();
            people.Add(new Person("Steve"));
            people.Add(new Person("Jake"));
            people.Add(new Person("Tyler"));
            people.Add(new Person("Evan"));
            people.Add(new Person("Gina"));

int count = people.Count(person => person.FirstName.ToUpper().Contains("N"));
Assert.That(count, Is.EqualTo(2));

As you know, List<T> does not include by default a ‘Count’ method.

When we include a reference to System.Linq, it includes extensions that get added to any type of IEnumerable class.

Some more examples include:

  • Any – Returns true if any items meet the criteria.
  • Average – Returns an average of the field specified.
  • Count – Pretty straight forward (as shown above).
  • Where – Just like SQL, you can return a subset based on a condition.
  • OrderBy – Also just like SQL.

Let’s give some examples based on the list above:

bool any = people.Any(person => person.FirstName.Contains(“Steve”));

Assert.That(any, Is.True);

IOrderedEnumerable<Person> peopleSearch = people.Where(person => person.FirstName.Contains(“a”)).OrderBy(person => person.FirstName);

Using ‘where’ with ‘OrderBy’:

IOrderedEnumerable<Person> peopleSearch = people.Where(person => person.FirstName.Contains(“a”)).OrderBy(person => person.FirstName);

So, how do you create an Extension method?

Let’s create a simple example where you would want to validate the string email address, for example:

 

string email = "steve@steve.com";
email.IsValidEmailAddress();

As we know, string doesn’t contain a ‘IsValidEmailAddress()’, we can add this functionality by extending string using a static class/method:

ie.

 

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

There is much more to this than I’ve shown here, but it should be a good start!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s