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!

Lambda Expressions Demonstration

I’ve been learning some of the new C# language features in the 3.5 framework. One of them is lambda expressions.

I’ve been a big fan of using delegates to search through lists, etc… and lambda is going to help shorten the code to do this. Below is a simple example showing the ‘new’ and the ‘old’ way:

        [Test]
        public void UsingLambdaTest()
        {
            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"));

            //with lambda - new:
            var namesWithanN = people.FindAll(name =>
                               name.FirstName.ToUpper().Contains("N"));

            Assert.That(namesWithanN.Count, Is.EqualTo(2));

            //with delegate - old:
            List<Person> peopleWithLetterN = people.FindAll(delegate(Person name)
                                                                {
                                                                    return (name.FirstName.ToUpper().Contains("N"));
                                                                });

            Assert.That(peopleWithLetterN.Count, Is.EqualTo(2));
        }

The use of the var is still typed, and the use of ‘name’ above has intellisense in Visual Studio 2008.

A cool feature here is the available options with var.

ie. take that subset and get a list of those returned:

List<Person> peopleWithN = namesWithanN.ToList<Person>();

More to come… Merry Christmas everyone!

MS MVC.NET – Extensions CTP Preview Released

Microsoft has releases the preview that includes support for the MS MVC.

Read more about it here

More on the ASP.NET MVC Framework:

Enjoy!