Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 views
in Technique[技术] by (71.8m points)

c# - .NET compiler and "Not all code paths return a value"

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 (param)
        test = false;
    else
        test = false;
    if (!test)
        return false;
}

error CS0161: Not all code paths return a value!

The code can be refactored - but the compiler is not suggesting that. Yet all return paths are covered - so why does the compiler complain that they are not?

Edit: I guess the conclusion here is that:

(error CS0161) + (all code paths obviously return a value) => refactor code.  

Once you get the habit of that translation I guess everything is ok.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...