Best way to check for null parameters (Guard Clauses)

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

    In C# 8.0 and later, new helps are available. C# 8.0 introduces non-nullable reference types (a feature somewhat confusingly called "nullable reference types" in the docs). Prior to C# 8.0, all reference types could be set to null. But now with C# 8.0 and the 'nullable' project setting, we can say that reference types are by default non-nullable, and then make our variables and parameters nullable on a case-by-case basis.

    So whereas at the moment, we recognize code like this:

    public void MyFunction(int thisCannotBeNull, int? thisCouldBeNull)
    {
        // no need for checking my thisCannotBeNull parameter for null here
    }
    

    If you set enable for your C# v8.0+ project, you can do things like this too:

    public void MyFunction(MyClass thisCannotBeNull, MyClass? thisCouldBeNull)
    {
        // static code analysis at compile time checks to see if thisCannotBeNull could be null
    }
    

    The null-checking is done at compile-time, using static code analysis. So if you've coded it in a way that means a null could turn up there, you'll get a compiler warning (which you can upgrade to an error if you want). So lots (but not all) of the situations where you need a run-time check for null parameters can be handled as a compile-time check based on your code.

提交回复
热议问题