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

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.



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

Verify your Comment

Previewing your Comment

This is only a preview. Your comment has not yet been posted.

Your comment could not be posted. Error type:
Your comment has been posted. Post another comment

The letters and numbers you entered did not match the image. Please try again.

As a final step before posting your comment, enter the letters and numbers you see in the image below. This prevents automated programs from posting comments.

Having trouble reading this image? View an alternate.


Post a comment

Your Information

(Name and email address are required. Email address will not be displayed with the comment.)