26 November 2007

String extension methods

C# 3.0 features the new extension methods. This basically seems to allow you to add your own methods to sealed classes. That seems a bit weird, and Microsoft gives the following advice in the Visual Studio 2008 help
In general, we recommend that you implement extension methods sparingly and only when you have to. Whenever possible, client code that must extend an existing type should do so by creating a new type derived from the existing type.
Full article Then try to make a List<> and bring up the Intellisense box. You will see 40-50 new methods, and by now you will guess they are all extension methods. Practiced what thy preached, Microsoft! Anyway, if Microsoft makes a lot of extension methods, so can we. We can now finally get rid of our 'utility' classes and make something like this:
namespace LocalJoost.Utilities
{
    public static class StringExtensions
    {
        public static string Reverse(this string s)
        {
            StringBuilder builder = new StringBuilder();
            for (int i = s.Length - 1; i >= 0; i--)
            {
                builder.Append(s.Substring(i, 1));
            }
            return builder.ToString();
        }
    }
}
And then we can do something like this:
string test = "Hello hello";
string reversed = test.Reverse();
The string "reversed" will now contain the string "olleh olleH". Notice the "this" keyword before the string s in method Reverse of class StringExtensions - that is the thing that defines Reverse as an extension method of string. The only further requirements are that both class and method implementing the extension are static.

2 comments:

Sander Soeteman said...

C# is beginning to look more and more like a strongly typed JavaScript. Wouldn't deriving from the string class and then adding you own method be a "cleaner" approach?

Joost van Schaik said...

That would indeed be a cleaner approach but sometimes this is not possible - like when the original class' designer has declared the class 'sealed'