Tuesday, June 14, 2011

Extension methods

In my previous post I talked about convenience functions and their usefulness in wrapping base level functionality. .Net 3.5 added a new feature called extension methods that allows methods to be added to a base class then called on instances of that class.

For example say you have an existing StringUtils class and method named OccurencesOf:

/// <summary>
/// StringUtils provides a collection of static functions for string manipulations.
/// </summary>
public static class StringUtils {

    /// <summary>
    /// Returns the number of occurences of the match string in the source string
    /// </summary>
    public static int OccurencesOf(string sourceString, string matchString) {
      return Regex.Matches(sourceString, EscapeRegEx(matchString)).Count;
    }
}

For example:
    StringUtils.OccurencesOf("the quick brown fox jumped over the lazy dog", "the");

With extension methods this can be rewritten like:
public static class StringExtensions {
 
    /// <summary>
    /// Returns the number of occurences of the match string in the source string.
    /// </summary>
    public static int OccurencesOf(this String sourceString, string matchString) {
        return Regex.Matches(sourceString, EscapeRegEx(matchString)).Count;
    }
}

And called like:
    "the quick brown fox jumped over the lazy dog".OccurencesOf("the");

Definitely a neat feature but in my next post I will explain why you shouldn't use extension methods.

No comments: