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

前端 未结 5 1678
臣服心动
臣服心动 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

    Let's backward analyze the code:

    Problem: Code doesn't return any value.

    Question: Where in code a value is returned?

    Answer: Just at the last line.

    Conclusion: So that line of code (last line) should always return a value.

    Question: Does last line always return a value?

    Answer: No, it only returns value if test is false while it has been set to true at the first line.

    Conclusion: As compiler says, this function never returns a value while it is supposed to return bool.

提交回复
热议问题