CA1062: Validate parameter is non-null before using it

When you have a public method that isn’t null checking its parameters, then you’ll get the CA1062 code analysis warning. This is part of the Nullable Reference Types feature.

For example, the following code isn’t null checking the movieRepository parameter:

public class StreamingService
{
	public void LogMovies(MovieRepository movieRepository)
	{
		foreach (var movie in movieRepository.GetMovies())
		{
			Console.WriteLine(movie.Name);
		}
	}
}
Code language: C# (cs)

This results in the CA1062 code analysis warning:

CA1062 In externally visible method ‘void StreamingService.LogMovies(MovieRepository movieRepository)’, validate parameter ‘movieRepository’ is non-null before using it. If appropriate, throw an ArgumentNullException when the argument is null or add a Code Contract precondition asserting non-null argument.

There are a few good options for solving this problem: check for null or suppress the warning. You’ll have to decide which option makes sense in your situation.

Option 1 – Check for null

It’s generally a good idea to null check your parameters. If the parameter is null, you can throw an exception, return some special result, or perhaps use a default value instead.

In this example, it’s throwing an ArgumentNullException.

public void LogMovies(MovieRepository movieRepository)
{
	if (movieRepository == null)
		throw new ArgumentNullException(nameof(movieRepository));


	foreach (var movie in movieRepository.GetMovies())
	{
		Console.WriteLine(movie.Name);
	}
}
Code language: C# (cs)

Option 2 – Suppress the warning

Let’s say you are sure the parameter won’t be null. Or if it’s null, you’re OK with it blowing up and throwing a NullReferenceException. In this case, you can suppress the warning with a pragma, like this:

public void LogMovies(MovieRepository movieRepository)
{
#pragma warning disable CA1062 // Validate arguments of public methods
	foreach (var movie in movieRepository.GetMovies())
	{
		Console.WriteLine(movie.Name);
	}
#pragma warning restore CA1062 // Validate arguments of public methods

}
Code language: C# (cs)

I wouldn’t recommend suppressing this code analysis rule for the entire project. You should take it on a case by case basis and determine if it’s ok to suppress it for the specific scenario.

Note: You can also add [NotNull] to the parameter to ignore the warning. If you’re using FxCop, this will make it ignore the problem. [NotNull] does not seem to make any difference when using .NET Analyzers (this might be a bug).