-3

I am making a program to switch to different Algorithms. I would love to know if you could reuse variables in a switch statement.

I have tried looking it up and changing to global and final but nothing seems to work

enter code here

switch(nr){

case 1: //For one algorithm
Console.Write("Write your base: ")
double b = convert.ToInt32(Console.Readline())

break;

case 2: //For the second algorithm but with the same name on the variable 
Console.Write("Write your second base: ")
double b = convert.ToInt32(Console.Readline())  <<<<< //ERROR on this line
break;


}

I did not expect this too happen due to its different cases

struct System.Double

Represents a double-precision floating point number

  • So, what is the error message? Read it carefully, you already have your answer. – Steve Sep 02 '19 at 22:02
  • C-derived languages (and others too) have the concept of variable _**scope**_. For the most part, the scope of a variable is the extent of the pair of curly brackets (`{}`) that contains the variable's declaration. You can only declare a variable once in a single scope (the rules are more complicated, but that's a simple summary). You declare `b` twice, so the compiler complains. @Alejandro's answer below hoists the declaration outside the switch statement, allowing b to be used twice. Note that even if you had declared b once in the switch, it wouldn't have been usable outside of the switch – Flydog57 Sep 03 '19 at 00:02

1 Answers1

2

Try this:

int b;

switch(nr){

case 1: //For one algorithm
    Console.Write("Write your base: ");
    b = Convert.ToInt32(Console.ReadLine());
break;

case 2: //For the second algorithm but with the same name on the variable 
    Console.Write("Write your second base: ");
    b = Convert.ToInt32(Console.ReadLine());  <<<<< //ERROR on this line
break;


}
Marcel Gosselin
  • 4,610
  • 2
  • 31
  • 54
  • For anyone getting "cannot use instance before it is declared" error, remove all instantiations of the variable in the cases – Max Jan 10 '20 at 10:37