Thursday, May 14, 2009

Lambda Expression

Good article that explains lambda expressions:

http://www.developingfor.net/c-30/upgrade-your-c-skills-part-3-lambda-expressions.html

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"

Example:

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}"