Best way to check for null parameters (Guard Clauses)

For example, you usually do not want the parameters in the constructor to be zero, so it’s very normal to see something like

if (someArg == null) { throw new ArgumentNullException(nameof(someArg)); } if (otherArg == null) { throw new ArgumentNullException(nameof(otherArg)); } 

This is a bit cluttered with code.

Is there a better way to test the argument list argument than this?

Something like, "check all the arguments and throw an ArgumentNullException if any of them is null and provides you with arguments that were empty.

By the way, with respect to recurring claims questions, this is not about labeling the arguments with attributes or something that is built-in, but that some people call it Guard Clauses to ensure that the object receives initialized dependencies.

+14
constructor c # arguments
source share
5 answers
 public static class Ensure { /// <summary> /// Ensures that the specified argument is not null. /// </summary> /// <param name="argumentName">Name of the argument.</param> /// <param name="argument">The argument.</param> [DebuggerStepThrough] [ContractAnnotation("halt <= argument:null")] public static void ArgumentNotNull(object argument, [InvokerParameterName] string argumentName) { if (argument == null) { throw new ArgumentNullException(argumentName); } } } 

using:

 // C# < 6 public Constructor([NotNull] object foo) { Ensure.ArgumentNotNull(foo, "foo"); ... } // C# >= 6 public Constructor([NotNull] object bar) { Ensure.ArgumentNotNull(bar, nameof(bar)); ... } 

DebuggerStepThroughAttribute very convenient, so in case of an exception during debugging (or when I attach the debugger after an exception occurs) I will not get inside the ArgumentNotNull method, but instead in the calling method, where the reference is actually null.

I use ReSharper contract annotations .

  • ContractAnnotationAttribute guarantees that I will never describe the argument ( "foo" ), and will also automatically rename it if I rename the character foo .
  • NotNullAttribute helps ReSharper in code analysis. So if I make a new Constructor(null) , I get a warning from ReSharper that this will throw an exception.
  • If you don’t like to annotate your code directly, you can do the same with external XML files that you can deploy in your library and which users can reference in their ReShaprer.
+15
source share

If you have too many parameters in your constructors, you better review them, but that's another story.

To reduce the template validation code, many guys write Guard utility classes as follows:

 public static class Guard { public static void ThrowIfNull(object argumentValue, string argumentName) { if (argumentValue == null) { throw new ArgumentNullException(argumentName); } } // other validation methods } 

(You can add other validation methods that may be necessary for this Guard class).

Thus, to check the parameter, only one line of code is required:

  private static void Foo(object obj) { Guard.ThrowIfNull(obj, "obj"); } 
+11
source share

Zero links is one of the problems you have to defend yourself with. But they are not the only ones. The problem is wider than this, and it boils down to the following: the method accepts instances of a certain type, but cannot process all instances.

In other words, the scope of a method is larger than the set of values ​​it processes. Protection clauses are then used to assert that the actual parameter does not fall into this β€œgray zone” of the method domain, which cannot be processed.

Now we have null references, like a value that usually goes beyond the valid set of values. On the other hand, it often happens that some non-zero elements of a set are also unacceptable (for example, an empty string).

In this case, it may turn out that the method signature is too wide, which indicates a design problem. This can lead to a redesign, for example. defining a subtype is usually a derived interface that limits the scope of the method and eliminates some of the defensive suggestions. You can find an example in this article: Why do we need security disclaimers?

+6
source share

There is a special package called SwissKnife . Install SwissKnife from the nuget gallery . It provides you with a lot of options, starting with zero checking Argument.IsNotNullOrEmpty(args,"args") arguments in SwissKnife.Diagnostics.Contracts namespace along with idoim option and many others. You can set Option<Class_Name> _someVar and then check if _someVar.IsSome or _someVar.IsNone . It also helps against nullable classes. Hope this helps.

+1
source share

You can try my Heleonix.Guard library, which provides security features.

You can write security points as shown below:

 // C# 7.2+: Non-Trailing named arguments Throw.ArgumentNullException(when: param.IsNull(), nameof(param)); // OR // Prior to C# 7.2: You can use a helper method 'When' Throw.ArgumentNullException(When(param.IsNull()), nameof(param)); // OR Throw.ArgumentNullException(param == null, nameof(param)); // OR Throw.ArgumentNullException(When (param == null), nameof(param)); 

It provides the throwing of many existing exceptions, and you can write your own extension methods for custom exceptions. In addition, the library references the Heleonix.Extensions library with predictive extensions such as IsNull , IsNullOrEmptyOrWhitespace , IsLessThan and many others to check your arguments or variables against the required values. Unlike some other security libraries with flexible interfaces, these extensions do not generate intermediate objects, and since the implementation is really simple, they are productive.

+1
source share

All Articles