1

I am learning C# at the moment. In the example below, I believe I have the correct code but there must be an error or two (maybe more) somewhere. Please see the code below:

    public static string ReturnAgeGroup(int age)
    {
        if (age >= 65)
        {
            return "senior citizen";
        }
        if (age < 21)
        {
            return "minor";
        }
        if (age >= 21 & age < 65)
        {
            return "adult";
        }
    }

There is a red squiggly line underneath RetrunAgeGroup, which says not all code paths return a value when I hover over it. Why is this? Every possibility, regarding age, is covered by the conditions.

Is/are there any other error(s) that I have failed to identify?

Regards

S.Dan
  • 37
  • 1
  • 5

4 Answers4

1

you can do like this.

public static string ReturnAgeGroup(int age)
{
    if (age >= 65)
    {
        return "senior citizen";
    }
    if (age < 21)
    {
        return "minor";
    }

    return "adult";
}
Huan Jiang
  • 247
  • 4
  • 13
0

IntellySence cannot be sure, that you variable realy 100% passes into one of IFs. Replace last if to else.

public static string ReturnAgeGroup(int age)
{
    if (age >= 65)
        return "senior citizen";
    if (age < 21)
        return "minor";
    else
        return "adult";
}
KamikyIT
  • 314
  • 2
  • 15
0

You need a return outside of the if statements, or to remove one of your cases and use it as default. For example, if we were to us adult as default we would do something like this:

 public static string ReturnAgeGroup(int age)
 {
     if (age >= 65)
     {
         return "senior citizen";
     }
     if (age < 21)
     {
         return "minor";
     }
     return "adult"; 
  }
David Watts
  • 2,249
  • 22
  • 33
0

Remove last if and just leave return "adult".

Compiler doesnt consider conditions, when it validates code paths. It's like street signs. If it says, that you can go left or right, then you can. Compiler dont care, if just after the turn there's huge pile of garbage and road is unpassable. Similar here. There's 3 conditions, which might or might not be true. Since after last one there's no more code and your function is expected to return value under all circumstances you get that warning.

Radosław Cybulski
  • 2,952
  • 10
  • 21