Why you want extension methods? Just an exampleImagine a collection of the type HashTable or Dictionary. It is sometimes convenient to retrieve ANY element of the collection. You don’t want the first, you don’t want the last (it would be a non-sense talking about order in a hash table). You don’t want any element in special, just one. The default HashTable or Dictionary collections don’t have a GetAnyElement() method, so you would typically iterate through the collection getting the first element you find.
If this operation is done frequently over your code, and you are a clever developer, you won’t be duplicating the same piece of code all around, and you will end up with some sort of static code like this:
That is what extension methods give you. Pretty much like ExtenderProviders do at design time, adding properties to controls, ExtensionMethods tell the environment that the GetAnyValue() method is in fact a part of the specific Dictionary instance, so the invocation to the method is through each instance, not through an additional class.
The following is the old way of doing this stuff. Create a static class with some utility methods, and invoke them:
What do I need to use them?Theoretically, Extension Methods were introduced in .Net 3.0. However, if you try to use them directly, your compiler will say that needs a reference to System.Core.Dll. If you add that reference, you will realize that in fact is a .Net 3.5 dll. So, here you can follow two different paths:
1.- Add a reference to System.Core.Dll, deploy your application as .Net 3.5, and jump to the next chapter
2.- If deploying your application as .Net 3.5 is not an option, you can always add the following code snippet:
How to write them?Now you are ready to write your own extenders. Let’s see the example code for the GetAnyValue extension method:
The Type you specify on the right of the “this” keyword will state the kind of objects this method extends. Once you have the code, just add a “using” sentence (to the namespace you used for your “extenders” class) in every source file where you want to use them. Et voilá! Method extended… Easy as that:
Of course, you can combine this with Generics (using the <T> generic type), to make things even more functional.
Another useful example: A WordCount method for the string typeIn this MSDN page, you can find another useful example: a WordCount method for the “string” type.