August 20, 2016 · C#

Calling C# Extension Methods on null references

Many C# developers are familiar with extension methods, but did you know that you can call extensions methods on null objects without fear of the dreaded Object reference not set to an instance of an object. error that comes along with invoking a method on a null reference.

Consider the extension method

public static bool IsNullOrEmpty(this string str)  
{
    return string.IsNullOrEmpty(str);
}

Notice, we don't actually try and invoke anything on str, we just pass it through to the string.IsNullOrEmpty() method for checking.

Provided that we're working with a string variable (which provides us with our IsNullOrEmpty() extension method, we can invoke the method without fear:

string str = null;  
Console.WriteLine("Is null or empty?: {0}", str.IsNullOrEmpty());

// OUTPUT:
Is null or empty? True
  • LinkedIn
  • Tumblr
  • Reddit
  • Google+
  • Pinterest
  • Pocket
Comments powered by Disqus