two switch in visual C #

1

Can I make two switches in the same method in visual C #? I try to do it and in the second switch I get an error message that says unreachable code. thanks for the help.

private bool CalcularLibro() {
  switch (TipoPasta.ToUpper()) { 
    case "LUJO": 
                 ValorPasta = 10000; 
                 return true; 
    case "NORMAL":
                 ValorPasta = 5000;
                 return true; 
    default: 
            Error = "No definió el tipo de pasta";
            return false; 
} 

  switch (TipoPpel.ToUpper()) { } 
}
    
asked by Alejandro Álvarez Muñoz 01.10.2018 в 04:12
source

1 answer

7

Your code can not get to execute the second switch, it is impossible and I explain the reason. When you define your CalculateBook method, you indicate that you are going to return a Boolean, so far, the problem is now.

When making the first switch, you have indicated that in any of the 3 cases it covers, return true or false, which means that returning a value can not continue, it is logical.

Whenever it goes through a return true or false it will end the execution of your method because it already returns what it has to return, so it ends its execution.

To avoid this, do not use return inside the switch (unless you need it), your code can be something like that without knowing that second switch what it does:

private bool CalcularLibro() {

  bool esPasta = false;   //Definimos un bool y será este el que devolvamos

  switch (TipoPasta.ToUpper()) { 
    case "LUJO": 
             ValorPasta = 10000; 
             esPasta = true;    //Pasamos nuestra variable a true
             break;             //Ponemos break para salir del switch
    case "NORMAL":
             ValorPasta = 5000;
             esPasta = true;    //Pasamos nuestra variable a true
             break;             //Ponemos break para salir del switch
    default: 
             Error = "No definió el tipo de pasta";
             esPasta = false;   //No ponemos break porque es la última opción del switch
  } 

  switch (TipoPpel.ToUpper()) { }   //Hacemos lo que tengamos que hacer aquí

  return esPasta;  //Devolvemos el bool con el resultado que hayamos obtenido
}
    
answered by 01.10.2018 в 08:00