Thursday 29 September 2011

Extension methods

What are Extension Methods?

Extension methods allow you to extend an existing type with new functionality, without having to sub-class or recompile the old type. Extension Methods help blend the flexibility of "duck typing" support popular within dynamic languages today with the performace and compile-time validation of strongly-typed languages. This is a cool feature of C# 3.0

Extension Method Example:

Lets say you want to check if a variable string is a valid telephone number. In this example, our valid telephone number must start with a zero and followed by 9 more digits or start with a zero followed by two digits a space three digits a space and four digits (0787845122 or 078 784 5122). You would normally implement this by calling a separate class (most likely a static method) to check to see whether the string is valid, for instance:

string telephone = txtTelephone.Text;

if ( MyValidator.IsValidTelephone(telephone) ) {

}

Now using extension method, i can add a useful IsValidTelephone() method onto the string itself, which returns whether the string instance is a valid string or not. I can then re-write the above code to be cleaner and more informative like:






















Note that the static method above has a "this" keyword before the first parameter argument of type string. This tells the compiler that this particular Extension method should be added to objects of type "string". Within the IsValidTelephone() method implementation i can then access all of the public properties/methods/events of the actual string instance that the method is being called on, and return true/false depending on whether it is a valid telephone or not.
Hope you enjoyed this post, will add some example in the next post.