C# 3.0 Method Extenders

“Method Extenders” is one of the most useful features introduced in the third version of .Net, which allows us to extend the features of a pre-built class. This small post will show you why you want them, how to use them, and the different versions of .Net you will need to deploy.

Why you want extension methods? Just an example

Imagine 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:
        public static string GetAnyValueOfDictionary(Dictionary<string, string> pDictionary)
        {
            foreach (string value in pDictionary.Values)
                return value;
            return "";
        }
This is nice, but… Wouldn’t it be muuuuuuch nicer if that method was shown as an instance method (automatically recognized by the IntelliSense) instead of a static one inside a different class?
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:
            // Old fashioned
            Dictionary<string, string> myDictionary = new Dictionary<string, string>();
            string anyValue = DictionaryUtils.GetAnyValueOfDictionary(myDictionary);
This forces you to remember that there’s a DictionaryUtils class holding that code. Not anymore… This is the new way:
            // Extension Methods
            Dictionary<string, string> myDictionary = new Dictionary<string, string>();
            string anyValue = myDictionary.GetAnyValue();
Fancy uh?

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:
namespace System.Runtime.CompilerServices
{
    public class ExtensionAttribute : Attribute { }
}
This will allow the compiler to work with Extension Methods even in a .Net 2.0 application, as this blog post explains deeply.

How to write them?

Now you are ready to write your own extenders. Let’s see the example code for the GetAnyValue extension method:
 public static string GetAnyValue(this Dictionary<string, string> source)
        {
            foreach (string key in source.Values)
                return key;
            return "";
        }
As you can see, Method Extenders are written as static methods (inside a static class). Of course, you need a reference to the calling instance object, that’s why the infrequent word this appears in the parameters declaration.
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:
image
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 type

In this MSDN page, you can find another useful example: a WordCount method for the “string” type.
            public static int WordCount(this string str)
            {
                return str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length;
            }
Of course, you can put there your own split char preferences, but it’s indeed a handy method, isn’t it?
Take Care!

Detecting if a piece of code is running in Design Time

Sometimes, you will want to distinguish if a certain piece of your code is being executed at run-time or as a part of the Visual Studio Design-Time calls.

A very easy way of checking this is:

bool isDesignTime = (this.Site != null && this.Site.DesignMode == true);

Why to explain this?

This is something quite obvious, but some people ask in the forums why they are receiving an exception when trying to open the design view of a form, in Visual Studio. Those exceptions can be caused by many things, but the one explained here is one of the frequent reasons.

Use case

Imagine you have developed a custom UserControl class, which needs to do something everything it´s made visible. You will probably override the OnVisibleChanged event to perform that operation. Now, imagine that operation can only be done at runtime. For example, if you need in that operation some data to be loaded, data that won´t be available at Design-Time. Now, imagine that you insert that UserControl into one of your forms.

As you can probably imagine, each time you open that form in the Design View of VisualStudio, the overriden OnVisibleChanged event will be fired, and as that data is not available, you will receive an exception, ruining the initialization of the DesignView, and banning you from editing anything at design time in your form.

In such cases, using the above check will save you from this behavior. Just put that check in the OnVisibleChanged event, and use the mentioned data only if not in Design Time. Et voilá. You have design view operative again.

Cheers!