Extension methods in C# 3.0
C# 3.0 provides a very useful feature named Extension Methods. Extension methods allow you “extend” existing classes by giving you the ability to define new methods on them. For example, I can implement my very own method, say MyStringMethod(), on the existing .NET System.String class. I would then be able to call this method like any other method in String class:
string s = ""; s.MyStringMethod();
Pretty neat, huh? But besides the syntactic sugar, there are a few additional advantages to using extension methods:
- Extension methods are fully supported by Visual Studio Intellisense making them easier to discover. Thus whenever someone, provided that he/she is using my library, types in ‘string.’, Intellisense will display my method as well.
- The other advantage is related to overall system design and usability. If you’ve been programming for a while, then you’ve probably used and/or implemented utility methods. Typically these are public static methods like:
public static object Clone(object from, object to); public static cbool IsNumeric(string s); public static string FormatDateTime(DateTime d, int timeZoneOffset);
Overtime the utility classes get bigger and bigger making the methods inside them more and more obscure. This can even result into the same method being implemented twice, especially so if you have multiple utility classes that aren’t very well defined. By turning these methods into extension methods we make them easier to find and thus avoid duplication.
So how do we turn them into extension methods? By adding the keyword ‘this’ in front of the parameter to which this method ought to belong. Below is what the above method declarations look like after we turn them into extension methods:
public static object Clone(this object from, object to); public static bool IsNumeric(this string s); public static string FormatDateTime(this DateTime d, int timeZoneOffset);
Note that the methods must be static and must belong to a static class. I personally prefer creating separate extensions classes to house the methods. So,
StringExtensions.cswill contain all my String extension methods,
DateTimeExtensions.cswill contain all my DateTime extension methods……and so on.
I hope you’ve found this post to be helpful and informative. Please leave your feedback and/or comments to help me improve. Thanks!
|
|
|
Nice post, though the example of how do you implement extension method would make it even better.
I’ve explained how to go about implementing one. But if you wish to see an actual implementation then read the blog entry on ‘Making ASP .NET Gridview a little less painful’. Thanks!