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:
Post a Comment