Using extension methods on null objects

One feature that is often disregarded in extension methods is that they get called for null objects. While instrumenting parts of OpenRasta, I faced the problem of having some classes not always created through the container. As such, sometimes their Log property would be null, and each call to a logging method would have to check for that condition. After doing a few back-and-forth, I settled on using an extension method, coupled with a null object.

Take a simple class, and add a Log property.

public class LoggingClass

{

    public ILogger Log { get; set; }

}

Then, create a simple extension method on the ILogger, and return a null object

        public static ILogger Safe(this ILogger logger)

        {

            if (logger == null)

                return NullLogger.Instance;

            else

                return logger;

        }

Now all the logging code can simply call the Safe() method to ensure that, in the absence of a logger, a null object will be used instead. The code using it looks like the following.

        public void DoSomething()

        {

            Log.Safe().WriteDebug("I did something!");

        }

Voila!

Ads

Comment