Tuesday, September 30, 2008

Extension Methods Done Right in C#

Extension methods are great! In the past I would simulate Extension methods by building Bookmark folders in Visual Studios for common string functions, math functions etc. I then migrated to using code snippet tools to save little reusable snippets of code, but always found it difficult for others to know that I had implemented a new code snippet and that they could now use it in their code. But alas, along came Extension methods and all my problems were solved. I now have a great way to organise all my code snippets into a contextual structure and also make it immediately available to the rest of the developers in my team. Below is a simple example of extending the Dictionary class to implement a "SortDictionary" method.

 static class DictionaryExtensions: IDictionary
        internal static Dictionary SortDictionary(this Dictionary data)
        internal static Dictionary<double, double>  SortDictionary(this Dictionary<double, double>  data)
            List<KeyValuePair<double, double> >  result = new List<KeyValuePair<double, double> > (data);
            delegate(KeyValuePair<double, double>  x, KeyValuePair<double, double>  y)
                return y.Value.CompareTo(x.Value);
            result.ForEach(delegate(KeyValuePair<double, double> dkvp) { data.Add(dkvp.Key, dkvp.Value); });

            return data;

Now from any class in my solution I can add a reference to this project containing this Extension Class and call the functionality as follows :

 Dictionary<double, double> UnsortedDictionary = new Dictionary<double, double> ();
Dictionary<double, double>  SortedDictionary = UnsortedDictionary.SortDictionary();

Hope this helps,
 - Tim

No comments: