Friday 18 September 2009

Extensions, extensions

Once again the .Net framework has brought out another fantastic feature which makes development smarter and easier.
 
Extensions are a very simple but very useful feature in .Net. so what are they? They are methods which extend the functionality of an existing object, what this means is that you the developer can add a method to any object (as far as I know!). For example, if we look at the boring String class we see methods such as Contains(), EndsWith(), Join(), LastIndexOf(), ToLower(), Trim() and many more! However what about the ConvertToMackolicious() method!!? It doesn’t exists! So everytime I want to convert a string to “Mackolicious“ I either have to create a private method or create a class.
 
The disadvantages, if I had 50 classes that required this functionality I would need at least 50 private methods! That’s dumb! So naturally I would create a class right, but every time my application gets compiled so would the class thus creating an unnecessary object in memory, boooo.
 
 Welcome extensions! Now I can write a static method within a static class and provide a certain method signature and  can achieve a functionality which is identical to the functionality of a regular instance method, such as those examples above.
 
This is an example of the syntax required for an extension method: public static string ConvertToMackolicious(this String stringObject){}. Using the keyword ‘this’ tells the runtime what object you are extending, here I’m extending a string, hence all strings within this scope (namespace) will be able to benefit from the ConvertToMackolicious() method yippee!
 
Disadvantages of extension methods (from my personal experience). Acting on an object within the .Net framework is easy and produces good results, however acting on a type built by yourself or someone else may not always be a good idea. The reason being that they might one day change the implementation of that type making your extended method produce wrong results or make it stop working altogether! Be careful!