Matthew Cioffi
Matthew Cioffi

Reputation: 11

All paths don't return a value

I'm not sure what exactly is wrong with my code because it was working before but now it's showing me this error.

main.cs(179,20): error CS0161: `CarProgram.ChangeGears(int, string)': not all code paths return a value

The program is for car functions, like a simulator in a way, but I want to get this first error out of the way before moving on to the rest.

Here's the code

private static int ChangeGears(int s, string g)
{
     Console.WriteLine("Inside the function Change Gears");
     if (s == 0)
     {
      string haveGear;
     Console.WriteLine("What gear would you like to have?");
     haveGear = Console.ReadLine();
     haveGear = haveGear.ToUpper();
     if (haveGear == "P" || haveGear == "R" || haveGear == "N" || haveGear == "D")
        {
            switch (haveGear)
            {
                case "P":
                {
                    Console.WriteLine("You are in park");
                    break;
                }

                case "N":
                {
                    Console.WriteLine("You are in neutral");
                    break;
                }

                case "D":
                {
                    Console.WriteLine("You are in drive");
                    break;
                }

                case "R":
                {
                    Console.WriteLine("You are in reverse");
                    break;
                }
            }//close
            g = haveGear;
        }
     else
     {
         Console.WriteLine("The speed must be 0 to change gears.");
     }
     Console.WriteLine("Gear is "+ g);

     return 0;
}
}// close ChangeGears

Upvotes: 0

Views: 74

Answers (2)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186678

Please, format out your routine,

private static int ChangeGears(int s, string g) {
  Console.WriteLine("Inside the function Change Gears");

  if (s == 0) {
    ...
    /* Some logic here */
    ... 
    return 0; // <- when s == 0 ChangeGears returns 0
  }

  //TODO: return value when s != 0
}// close ChangeGears

And you clearly see that ChangeGears doesn't return anything when s != 0

Upvotes: 3

Austin T French
Austin T French

Reputation: 5131

It's in the ChangeGears Method:

You are saying:

if(condition)
{
  // Do Stuff
  return 0;
}
// Here is implicitly:
if (not Condition)
{
  //Do nothing
}

The else also needs a return.

Additionally, the error message gives you the information you need.

main.cs(179,20): error CS0161

Is saying line 179 is the method with the issue.

Upvotes: 0

Related Questions