String extension methods
1 minute read
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:
public static class StringExtensions
public static string Reverse(this string s)
StringBuilder builder = new StringBuilder();
for (int i = s.Length - 1; i >= 0; i--)
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.