Posts

Showing posts from July, 2008

C# Extension Methods and Null References

With extension methods in C# 3.0, you can create methods that operate as if they were instance methods of other classes. You can "add" methods to any class, even to core classes like System.String and System.Object . This example creates two string extensions: public static class StringExtensions { public static string HtmlEncode(this string input) { return AntiXss.HtmlEncode(input); } public static int ToInt32(this string s) { return Int32.Parse(s); } } (I used the HtmlEncode method implemented in the Anti-Cross Site Scripting Library .) The way to use extension methods is to call them as if they were instances of the extended class itself (given as the first parameter to the extension methods): int input = "123".ToInt32(); ... string safeString = unsafeString.HtmlEncode(); Or you can use them as normal static methods (it has the same effect as above): int input = StringExtensions.ToInt32("123"); ... string safeStri