开发者

code will generate compile error [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance. Closed 11 years ago.

The following code will generate a compiler error.

string GetAgePhrase(int age) 
   {
     if (age > 50) return "Naresh";
     if (age > 30) return "Ravi";
     if (age > 10) return "Nagendra";
     if (age > 9) return "Jagan";
     if (age > 2) return "Raja";
   }

Which of the following statements, inserted as the last line of the function, woul开发者_运维问答d solve the problem?


The problem with this code is that not all paths of the code return a value... i.e. what if age is 0? You can fix this by adding after the last if statement return null this way if none of the conditions are met it will always have a return value.


Your method doesn't always return a value, so just a default return after all the if statements.

   string GetAgePhrase(int age) 
   {
     if (age > 50) return "Naresh";
     if (age > 30) return "Ravi";
     if (age > 10) return "Nagendra";
     if (age > 9) return "Jagan";
     if (age > 2) return "Raja";

     return null;
   }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜