C#: throw invalid expression compilation

后端 未结 2 1907

I\'m using this code in order to check queryable value:

visitor.Queryable = queryable ?? throw new Exception(\"error message\");
2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-11 14:18

    This feature is only available post C# 7.0. See under Throw exception of What's New in C# 7.0.

    If you are using an older VS and want to enable C# 7 features: Have a look at How to use c#7 with Visual Studio 2015? if not in VS 2017.


    If you are working with a previous version of the C# compiler, as you must be due to the error then you cannot use the ?? operator this way as the throw does not return a right operand value. As the C# Docs say:

    It returns the left-hand operand if the operand is not null; otherwise it returns the right operand.

    The pattern is like this:

    var result = someObject ?? valueToAssignIfWasNull;
    

    To solve it write instead:

    if(queryable == null)
    {
        throw new Exception("error message");
    }
    visitor.Queryable = queryable;
    

提交回复
热议问题