I finally got around to installing Orcas on my laptop this weekend. You are probably asking yourself, what took so long? Simple, my laptop did not have the spare 14gigs needed in order to get it up and running. It took some pretty major house cleaning in order to get enough spare space. Oh well, on to the post.
So, what exactly is an Extension Method? From the C# 3.0 Specs (found here) they are 'static methods that can be invoked using instance method syntax. In effect, extension methods make it possible to extend existing types and constructed types with additional methods.'.
To put it simpler terms they are methods that allow a developer to Extend any existing CLR type without the need to subclass that type.
A few notes from the C# Specs
- Extension methods are less discoverable and more limited in functionality than instance methods. For those reasons, it is recommended that extension methods be used sparingly and only in situations where instance methods are not feasible or possible
- Extension members of other kinds, such as properties, events, and operators, are being considered but are currently not supported
Steps to creating an Extension Method
- The class that holds the Extension Method MUST be static
- The method that is the Extension Method MUST be static
Ok, on to the code...
Creating your first Extension Method
You should notice something different about the above extension method. The 'this' keyword. The 'this' is a modifier on the method so the CLR knows the types on which the extension is allowed.
The next modifier is the CLR types the extension method can be used by. The above extension CANNOT be used by any other type then string. The value of the input param will be the current value of the variable (Be careful for null's).
For fun, create a double variable and try to use it. You cannot.
Using your Extension Method
In the above code, I have used my extension method on the string variable I created. You will notice that I did not have to do anything special in order to access the Extension Method. NOTE: If the extension method is NOT in the same namespace, you will have to import/reference that namespace in order to use it.
As you can see from this example, using Extension Methods is pretty straight forward and easy. But be careful not to over use these. Just because you CAN create/use Extension Methods does not mean you MUST use them. Like anything else, if you don't have a solid reason for using something, DON'T.
- C# 3.0 Specs here
- For real-world examples on when/how to use Extension methods check out Scott Gu's blog here.
07-08-2007 10:11 AM