Not all code paths return a value - where?

前端 未结 7 1194
我在风中等你
我在风中等你 2021-01-26 06:03

I have the following C# code. For reasons I won\'t go into, this is the required way of localising.

My problem is, I cannot for the life of me figure out what path is no

相关标签:
7条回答
  • 2021-01-26 06:28

    Maybe you could refactor it so that at the bottom of your code you have a SINGLE return statement. And all your decision-making code simply 'sets' the return value.

    Then in your switch(Name) block SET the value of what you want to return - then break out of the switch (rather than having a whole bunch of returns). IMO, this would make the code neater. Also, I think it'd make it easier to maintain.

    ie.

    switch(Name)
            {
                case "AppName":         retString = ResMain.GetString("$this.Text");
                case "MinimizeToTray":  retString = "Closing the program minimizes it to the tray. To fully quit the program, right-click the icon in your tray and choose Exit.";
                case "ReallyExit1":     retString = "Do you really want to exit?";
                case "ReallyExit2":     retString = "Torrents will not be checked and downloaded until you launch the program again!";
                default:                retString = "String not found!";
            }
    
    ...
    
    return retString;
    
    0 讨论(0)
  • 2021-01-26 06:29

    What is the purpose of the if-block? As far a I can see, if code below the switch is executed, StringNotFound will always be true so the if-block is not necessary, but it may very well confuse the code analysis.

    0 讨论(0)
  • 2021-01-26 06:29

    To prevent mistakes or puzzles like this, you better not do both of this (below) , as there is no single logical flow anymore when you:

    • Maintain a retVal variable, together with
    • Multiple uses of the return statement.

    Choose one solution:

    • only return a retVal variable, or
    • return a default at the bottom of the function.
    0 讨论(0)
  • 2021-01-26 06:34

    At the very end of your method, if StringNotFound is false:

    if(StringNotFound)
    {
       [...]
    }
    
    // missing return statement here
    
    0 讨论(0)
  • 2021-01-26 06:35

    If StringNotFound is false, you don't return anything.

    0 讨论(0)
  • 2021-01-26 06:38

    if(StringNotFound)

    If this is false there is no else statment to catch it.

    use

    if(StringNotFound)
    {
    //your code
    }
    Else
    {
    return "String not found!";
    }

    0 讨论(0)
提交回复
热议问题