.NET compiler and “Not all code paths return a value”

前端 未结 5 1669
臣服心动
臣服心动 2020-12-11 11:24

Why in code like below is the .NET compiler not able to establish that all code paths do return a value?

bool Test(bool param) {
    bool test = true;
    if         


        
5条回答
  •  隐瞒了意图╮
    2020-12-11 11:32

    From the C# Language Specification 4.0 included with Visual Studio 2010.

    10.6.10 "Method body":

    When the return type of a method is not void, each return statement in that method’s body must specify an expression that is implicitly convertible to the return type. The endpoint of the method body of a value-returning method must not be reachable. In other words, in a value-returning method, control is not permitted to flow off the end of the method body.

    The definition of reachability is here (emphasis added):

    8.1 "End points and reachability":

    If a statement can possibly be reached by execution, the statement is said to be reachable. Conversely, if there is no possibility that a statement will be executed, the statement is said to be unreachable.

    ...

    To determine whether a particular statement or end point is reachable, the compiler performs flow analysis according to the reachability rules defined for each statement. The flow analysis takes into account the values of constant expressions (§7.19) that control the behavior of statements, but the possible values of non-constant expressions are not considered.

    Since !test isn't a constant expression (even though it will always evaluate to true), the compiler is obliged to not consider it in the flow analysis. One reason (maybe the only reason) for this restriction is that performing this kind of flow analysis is impossible in the general case.

    To get rid of the error, you'll need to have another return statement, either in an else clause or unconditionally at the end of the method.

提交回复
热议问题