Best way to check for null parameters (Guard Clauses)

后端 未结 10 1805
北荒
北荒 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:28

    You might try my Heleonix.Guard library, which provides guard functionality.

    You can write guard clauses like 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 throwing of many existing exceptions, and you can write custom extension methods for custom exceptions. Also, the library refers to the 'Heleonix.Extensions' library with predicative extensions like IsNull, IsNullOrEmptyOrWhitespace, IsLessThan and many more to check your arguments or variables against desired values. Unlike some other guard libraries with fluent interfaces, these extensions do not generate intermediate objects, and since implementation is really straightforward, they are performant.

提交回复
热议问题