Best way to check for null parameters (Guard Clauses)

后端 未结 10 1921
北荒
北荒 2021-01-31 16:45

For example, you usually don\'t want parameters in a constructor to be null, so it\'s very normal to see some thing like

if (someArg == null)
{
    throw new Arg         


        
10条回答
  •  耶瑟儿~
    2021-01-31 17:27

    public static class Ensure
    {
        /// 
        /// Ensures that the specified argument is not null.
        /// 
        /// Name of the argument.
        /// The argument.
        [DebuggerStepThrough]
        [ContractAnnotation("halt <= argument:null")]        
        public static void ArgumentNotNull(object argument, [InvokerParameterName] string argumentName)
        {
            if (argument == null)
            {
                throw new ArgumentNullException(argumentName);
            }
        }
    }
    

    usage:

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

    The DebuggerStepThroughAttribute comes in quite handy so that in case of an excpetion while debugging (or when I attach the debugger after the exception occurred) I will not end up inside the ArgumentNotNull method but instead at the calling method where the null reference actually happend.

    I am using ReSharper Contract Annotations.

    • The ContractAnnotationAttribute makes sure that I never misspell the argument ("foo") and also renames it automatically if I rename the foo symbol.
    • The NotNullAttribute helps ReSharper with code analysis. So if I do new Constructor(null) if will get a warning from ReSharper that this will lead to an exception.
    • If you do not like to annotate your code directly, you can also do the same thing with external XML-files that you could deploy with your library and that users can optinally reference in their ReShaprer.

提交回复
热议问题