Search code examples
c#.netargument-validation

What is the best practice in case one argument is null?


when validating methods' input, I used to check if the argument is null, and if so I throw an ArgumentNullException. I do this for each and every argument in the list so I end up with code like this:

 public User CreateUser(string userName, string password, 
                            string Email, string emailAlerts, 
                            string channelDescription)
    {

        if (string.IsNullOrEmpty(userName))
            throw new ArgumentNullException("Username can't be null");

        if (string.IsNullOrEmpty(Email))
            throw new ArgumentNullException("Email can't be null");
       //etc, etc, etc
    }

Is this OK? Why should I do this? Would it be ok if I simply group all the checks and return a null value instead of throwing the exception? What is the best practice to address this situation?

PS: I want to change this, because with long methods, it gets very tedious to do so.
Ideas?


Solution

  • Make an ArgChecker class with something like this

      ArgChecker.ThrowOnStringNullOrEmpty(userName, "Username");
    

    where ThrowOnStringNullOrEmpty is

      public static void ThrowOnStringNullOrEmpty(string arg, string name)
      {
          if (string.IsNullOrEmpty(arg))
            throw new ArgumentNullException(name + " can't be null");
      }
    

    You could also try to process a list of arguments using a params arg, like:

      public static void ThrowOnAnyStringNullOrEmpty(params string[] argAndNames)
      {
           for (int i = 0; i < argAndName.Length; i+=2) {
              ThrowOnStringNullOrEmpty(argAndNames[i], argAndNames[i+1]);
           }
      }
    

    and call like this

      ArgChecker.ThrowOnAnyStringNullOrEmpty(userName, "Username", Email, "email");