VSTA
Lambda Expressions and Anonymous Methods

Extension Methods

C# 3.0 makes it possible to add methods to existing classes that are defined in other assemblies.

All the extension methods must be declared static. Extension methods are made by using the this keyword with the first parameter. Here I'm creating a Foo extension for the String class. These parameters can also be interfaces and generics to make it more flexible :-)

public static class MyExtension
{
   public static void Foo(this string s)
   {
      Console.WriteLine("extension method Foo invoked {0}", s);
   }
}

Now it's possible to invoke the Foo method like an instance method with a string. The string is passed with the first parameter of the method.

string s = "extensions are cool";
s.Foo();

In some future articles I will show some cool uses of this feature.

One important note from the C# specs:
Extension methods are less discoverable and more limited in functionality than instance methods. For those reasons, it is recommended that extension methods be used sparingly and only in situations where instance methods are not feasible or possible.

Christian

Comments

Feed You can follow this conversation by subscribing to the comment feed for this post.

The comments to this entry are closed.