blog @spotflux
These are the thoughts and opinions written by the spotflux team and our colleagues.
Show MenuHide Menu

Tech Tips: .NET Extension Methods

September 10, 2013

Not unlike Scala, C# (but probably to a lesser extent) blends principles from both Java and Racket; giving you more than enough rope to hang yourself with, but at least providing some nice conveniences like closures, type inference and our topic for today: extension methods.

From Microsoft’s extension method documentation:
“Extension methods enable you to “add” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.”

Put more simply, it allows you define instances methods in client code without having to touch the class source at all, and eliminates the need to have copious utility classes wherein you write a litany of static non-instance methods. So, instead of doing something like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MyNamespace
{
    public static class DictionaryUtil
    {
        public void ReplaceOrAdd(Dictonary<string, object> dictionary, string key, object value)
        {
            object obj = null;
            var has = dictionary.TryGetValue(key, out obj);
            if (has)
                dictionary[key] = value;
            else
                dictionary.Add(key, value);
        }
    }
}

You can write something like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Test.MyExtensions
{
    public static class DictionaryExtensions
    {
        public static void ReplaceOrAdd(this Dictionary<string, object> dictionary, string key, object value)
        {
            object obj = null;
            var has = dictionary.TryGetValue(key, out obj);
            if (has)
                dictionary[key] = value;
            else
                dictionary.Add(key, value);
        }
    }
}

While the two code snippets may seem almost exactly the same (because they are), only one of them (guess which) will allow you to do this:

Dictonary dict = new Dictionary();
dict.ReplaceOrAdd("key", new object());

Meanwhile the other will do this:

'System.Collections.Generic.Dictionary<string,object>' does not contain a definition for 'ReplaceOrAdd' and no extension method 'ReplaceOrAdd' accepting a first argument of type 'System.Collections.Generic.Dictionary<string,object>' could be found (are you missing a using directive or an assembly reference?)

While it’s certainly not a feature that’s going to make or break a project, it makes someone who’s compulsively worrying about clean code sleep a little easier at night.

 

Author: Phil