CS0161 "Program.Calculate (string, int, int)": not all branches of the code return a value. ConsoleApp1 C: \ Users \ Denis \ source \ repos \ calculateoncsharp \ ConsoleApp1 \ Program.cs

public static int Calculate(string action1, int a2, int a1) { switch (action1){ case "pi": return a1 + a2; case "mi": return a1 - a2; case "mu": return a1 * a2; case "de": return a1 / a2; default: Console.WriteLine("Error"); break; } } 
  • 3
    Everything is correct in default: no return - Alexander Muksimov
  • one
    1) either in default register return 2) or after the switch construction add return 3) or instead of return (in 1) or 2)) throw an exception if you do not know what value to return in the absence of the operator - gil9red
  • even with no default gives this error - Nikolay
  • one
    If there is no default , there will be no return if no case has fallen. Either enter return in default , or at the end of the method. - Suvitruf

3 answers 3

The correct solution is not to return some neutral value, but to throw an exception:

 public static int Calculate(string action1, int a2, int a1) { switch (action1){ case "pi": return a1 + a2; case "mi": return a1 - a2; case "mu": return a1 * a2; case "de": return a1 / a2; default: throw new ArgumentException(); } } 

Catch an exception and display an error message will be the caller:

 Console.WriteLine("Введите команду"); string action = Console.ReadLine(); try { int z = Calculate(action, x, y); } catch (ArgumentException) { Console.WriteLine("Команда неверна!"); } 
  • He wrote a similar answer, ahead. I want to add that it is not necessary to do return or throw in default . The compiler will be satisfied, for example, if you make a return or throw after the switch . And that of all the answers is not obvious. - 4per
  • @ 4per, well it is - yes. Usually this is what I write (you can save a line). The main thing is that all possible paths of execution of the code "rested" in return or throw - Andrey NOP

The method should in any case return an int. In the default branch, nothing is returned, so there is an error.

  • Add in default return -1, as an error designation. - Valery Losev
  • Well, we returned -1 and how to determine whether this value is normal or not? 2 minus 3 is also equal to -1 - Andrey NOP
  • I agree, therefore, when designing such methods, they generally do not. Usually, a separate method is created for each operation, even if it is single-line. And the int type is not suitable for such calculations. Double required. - Valery Losev

In default, you need to return some int type value that the function returns.

 public static int Calculate(string action1, int a2, int a1) { switch (action1) { case "pi": return a1 + a2; case "mi": return a1 - a2; case "mu": return a1 * a2; case "de": return a1 / a2; default: Console.WriteLine("Error"); return 1; //break; } }