code will generate compile error [closed]
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;
}
精彩评论