Friday, September 9, 2011

A Spoonful of Syntactic Sugar

One of the reasons I love developing with C# is the ease with which you can extend the language using facilities like generics, extension methods, and lambda expressions. As an old C++ coder, I feel very comfortable with a bizarre level of language extensiblity. Here's an example of what I'm talking about:

I was writing a library that scans an XML element tree, and I kept having the need to cast down from an XMLNode to an XMLElement. Naturally, to avoid runtime errors, I had to check the cast for success. The code looked something like this:


    foreach (var node in parentElement.ChildNodes)
    {
        var element = node as XmlElement;

        if (element != null)
        {
            ProcessElement(element);
        }
    }


After a while, this got pretty tiresome. I even started omitting the check for success out of fatigue, which of course led to run-time errors. Something had to be done! Fortunately C# provided a way to address this problem. I created the following extension method:


    public static class ExecByType
    {
        public static void IfType<T>(this T t, Action<T> d)
        {
            if(t != null)
            {
                d(t);
            }
        }
    }

This allowed me to change the code to something like this:


foreach (var node in parentElement.ChildNodes)
    {
        (node as XmlElement).IfType(e => ProcessElement(e));
    }


Which not only prevented errors, it also looks kind of exciting, so it's helping keep me awake while I finish my XML processing routines.