Framework Tips V: Extension Methods and nulls

You can call extension methods on null elements. It’s obvious when you think about it: its a normal static method where you specify its first parameter with this.

using System;

 

namespace ExtensionMethods2

{

    class Program

    {

        static void Main(string[] args)

        {

            string isNull = null;

            Console.WriteLine(isNull.IsNullOrEmpty());

            string isNotNull = "string";

            Console.WriteLine(isNotNull.IsNullOrEmpty());

        }

    }

 

    public static class StringExtensions

    {

        public static bool IsNullOrEmpty(this string s)

        {

            return s == null || s == "";

        }

    }

}

Notice that if it was normal instance method (i.e. defined in the System.String class) I would have to check if my string instance is not null, before calling it, or I would receive runtime NullReferenceException. Now I can move that check to the method, where it belongs, and make my code cleaner. Pretty slick 😉