Thursday, May 14, 2009

C# extention methods

Very nice feature.
According to definition: "Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type"


namespace ExtensionMethods
public static class MyExtensions
public static int WordCount(this String str)
return str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length;

And use it:
string s = "Hello Extension Methods";
int i = s.WordCount();

Note the following:
  1. Extensions should be defined in a static class
  2. Extensions should be defined in a static methods
  3. First parameter should be "this {class} {var}"

No comments:

Post a Comment