Check arguments for null in C#

 

I had a comment recently from ‘The Dag‘ asking if I could create some code which would check to ensure that none of the parameters for a methods were null. While this is quite a simple piece of code I thought I would reply in a post rather than answering in the comments as it is more likely to be found by anyone else who is looking to do the same.

The request is to allow for any number of parameters to be passed in and they all be checked, the suggested format by The Dag was;

Guard.NoArgumentsNull(() => arg1, arg2, arg3);

I didn’t keep to the format suggested exactly but I feel that the result meets all of The Dags requirements fully.

Breaking it down

The first part that I looked at was being able to pass in any number of arguments into the method to be checked for the presence of a null. The logical way of achieving this is by using a collection but .NET provides us with a method for passing in an unspecified number of arguments without having to create a collection object. This can be done through the use of the params keyword, which is the same way that you can receiving an unspecified number of arguments to a console application.

So the method currently looks like this;

public static bool AnyArgsNull(params object[] args)
{
    // Do something here
}

Now that we have a collection of objects we are able to use Linq to check if any of them are null. Which leaves our method looking like;

public static class Guard
{
    public static bool AnyArgsNull(params object[] args)
    {
        return args.Any(a => a == null);
    }
}

There’s nothing complicated about the final piece of code, it’s nice and simple to use for the task requested. The only problem I have with this is that it is not possible to identify which of the parameters were null and allow for the user to be notified that they need to ensure that they are passing that in. Personally I can’t think of any way of achieving this off the top but if you have any idea’s on how this could be achieved then please do post it in comment section below as I would be interested to see your implementations.