Tuesday, July 31, 2007

Extension Methods

This is the first in a series of posts that I will use to demonstrate some of the cool new features of the new C# 3.0 specification and Visual Studio 2008.

If you asked me, the two coolest new features of C# 3.0 are LINQ and Extension Methods. There have been a ton of articles demonstrating the power of LINQ, so I'll focus my first post on Extension Methods.

So what exactly is an extension method? In as few words as possible, it's a language feature that allows a developer to add new methods to existing types. And I see quite a bit of potential with this feature. For example, adding a SaveAsJpeg() method to the sealed System.Drawing.Bitmap class.

Just a little background so we can begin. An extension method must be declared in a static class, which makes a lot of sense when you think about it.

For demonstration purposes, let's create a static class called StringExtenstions that adds a Reverse() method to the string type.

public static class StringExtentions
{
public static string Reverse(this string str)
{
StringBuilder sb = new StringBuilder();

// Reverse the string
for (int i = str.Length - 1; i >= 0; i--)
{
sb.Append(str[i]);
}

return sb.ToString();
}
}


And believe it or not, that's it. You have just added a Reverse() method to all string types within your assembly. And how do you use it? Good question. Just like you would had the String class always had a Reverse() method.

string myString = "This is a test";
string reversed = myString.Reverse();


It should be noted that unlike regular methods, extension methods cannot access private members of the class that they are extending.

Stay tuned for more C# 3.0 goodness.

No comments: