Click here to Skip to main content
15,886,857 members
Articles / Programming Languages / C#

Extension methods to simplify null argument check

Rate me:
Please Sign up or sign in to vote.
3.00/5 (2 votes)
27 Nov 2011CPOL3 min read 33K   123   14   9
Shows how extension methods can be useful to reduce and reuse code for null argument check.

Introduction

Two rules that I like to follow while coding is 1) a method should not accept any null arguments and 2) a method should never return a null value. Following these very simple rules results in code which is simple to use more predictable and reliable. To follow rule one we always check the parameter for null value and throws <code>ArgumentNullException if its null. This results in lot of redundant code and reduces the readability of code. I will try to improve on this by using simple extension methods. 

Regular null check  

Lets have a look at how normal null parameter check looks like.

C#
public static Coffee GetCoffee(Milk milk, CoffeePowder coffeePowder, Sugar sugar)
   {
     if (milk == null)
       {
          throw new ArgumentNullException("milk", "Coffee without milk is not possible.");
       }

     if (coffeePowder == null)
       { 
          throw new ArgumentNullException("coffeePowder", "Coffee without coffeePowder is not possible.");
       }

     if (sugar == null)
       {
          throw new ArgumentNullException("sugar", "Sugarfree coffee is not supported");
       }

      // return tasty coffee as everything required is provided 
  }

The method is having too much of validation code which is not actually related to real implementation of the method.This certainly reduces readability of code.

Lets try Extension method

 Lets code the first extension method for object type itself. 

 

C#
public static class Extesnion
        { 
           public static void VerifyNotNull(this Object targetObject ,string parameterName,string message)
          {
              if (targetObject == null)
              {
                  throw new ArgumentNullException(parameterName,message);
              }
          }
        } 

The method looks very simple. Lets see how it can help to reduce code size in previous example.

C#
public static Coffee GetCoffee(Milk milk, CoffeePowder coffeePowder, Sugar sugar)
           {
             milk.VerifyNotNull("milk", "Coffee without milk is not possible.");

             coffeePowder.VerifyNotNull("coffeePowder", "Coffee without coffeePowder is not possible.");

             sugar.VerifyNotNull("sugar", "Sugarfree coffee is not supported");

               // return tasty coffee as everything required is provided
           }
  This extension method looks like silver bullet to me.It can be used to check null parameter of any type. It certainly helped to reduce code size and improved readability as well. But wait is it really good in all cases. No its not , because it will be accessible to all ValueTypes , since System.ValueType is also derived from ultimate base class i.e. Object. Also value types can not have null values and it is not required to check null for any of ValueType. Using this method for value types will result in boxing as well.Following code sample demonstrate the same problem.
C#
public void Coffee[] GetCoffee(int numberOfCups)                                    
        {
          numberOfCups.VefifyNotNull("numberOfCups" , "Number of cups is not specified.")
        } 

   So the silver bullet should be restricted to only objects of class. Fortunately this is possible and simple to do.Let modify the extension method.
C#
public static void VerifyNotNull<T>(this Object targetObject, string parameterName, string message)
                           where T : class
       {
           if (targetObject == null)
           {
               throw new ArgumentNullException(parameterName, message);
           }
       }

Only thing that is required is to make the method generic and apply class constrain using where keyword.
Is it a usable now? No its not. Because there are Nullable types as well.Null check extension method should be able to check null values of Nullable types.But our extension method is only restricted to class types where as Nullable types are in fact value types which can have null values. Lets have a overload that can satisfy the need. 

C#
public static void VerifyNotNull<T>(this T? targetObject, string parameterName, string message)
                                where T : struct
       {
           if (targetObject == null)
           {
               throw new ArgumentNullException(parameterName, message);
           }
       }

 So the bullet is shining now. There is some scope to improve by handling string types in better way. Usually checking only null is not sufficient for string types , as empty or string with only white space is equally unusable as null string in most cases. Lets have overload to support string differently than other types. 

C#
public static void VerifyNotNull(this string stringTargetObj, string parameterName, string message)
      {
         if (string.IsNullOrWhiteSpace(stringTargetObj))
          {
            throw new ArgumentNullException(parameterName, message);  
          }
      }

Lets see how it look like supporting all together. 

C#
private static Coffee GetCoffee(Milk milk, int? noOfCups, string deliveryPoint)
  {
     milk.VerifyNotNull("milk", "Coffee without milk is not possible.");

     noOfCups.VerifyNotNull("noOfCups", "Number of cups not defined.");

     deliveryPoint.VerifyNotNull("deliveryPoint", "Where to deliver the coffee cups?");
                
     //return delicious coffee     
  }   

  I have attached sample project for download with some extra overloads as supported by ArgumentNullExcption class.  Some unit testing is done using Nunit.

Points of Interest   

  Extension methods are definitely helpful to improved the null parameter check. Ideally I would like to have similar feature with no code solution.May be AOP can help in that case or if the compiler itself support this by means of attributes which will allow to map parameter name and exception messages in resources file. I hope this will be supported in future. Till that time I have some extension methods for rescue.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer Honeywell Automation India Ltd.
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionCorrection Pin
Member 1231001911-Nov-16 7:40
Member 1231001911-Nov-16 7:40 
QuestionI find the notion offensive Pin
muhahahahahahaa28-Nov-11 1:02
muhahahahahahaa28-Nov-11 1:02 
QuestionSystem.Diagnostics.Contracts.Contract Pin
SergeyT227-Nov-11 7:26
SergeyT227-Nov-11 7:26 
QuestionThoughts Pin
PIEBALDconsult27-Nov-11 3:36
mvePIEBALDconsult27-Nov-11 3:36 
Suggestionsuggestion Pin
ZGelic27-Nov-11 2:44
ZGelic27-Nov-11 2:44 
QuestionA Good start! Pin
VallarasuS27-Nov-11 2:34
VallarasuS27-Nov-11 2:34 
SuggestionIf you liked this article... Pin
Pablo Aliskevicius27-Nov-11 0:39
Pablo Aliskevicius27-Nov-11 0:39 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.