Home > Enterprise >  c# switch function error, maybe a misunderstanding of the format?
c# switch function error, maybe a misunderstanding of the format?

Time:12-25

hello I tried using this code to create a mini currency converter for my assignment but I don't understand why it doesn't work, please let me know why it might be so, thanks.

the error says that newValue has already been defined.

switch (userCurrency)
                {
                    case "USD":
                        double newValue = userEuro * usd;
                        break;

                    case "GBP":
                        double newValue = userEuro * gbp;
                        break;

                    case "CHF":
                        double newValue = userEuro * chf;
                        break;

                    case "AUD":
                        double newValue = userEuro * aud;
                        break;

                    case "CAD":
                        double newValue = userEuro * cad;
                        break;
                    default:
                        Console.WriteLine("Invalid input!");
                        break;

                }

CodePudding user response:

Instead of declaring newValue inside every case: declare it once (without assigning a value) above the switch, and just assign a value inside each case.

Or maybe use a "switch expression" instead.

CodePudding user response:

define "newValue" before the switch statement:

double newValue;
switch (userCurrency)
{
   case "USD":
     newValue = userEuro * usd;
   break;
...

CodePudding user response:

Extract the newValue declaration outside of the switch case block scope and then assign it inside the different switch cases

double newValue;
switch (userCurrency)
{
    case "USD":
       newValue = userEuro * usd;
       break;

    case "GBP":
        newValue = userEuro * gbp;
        break;

    case "CHF":
        newValue = userEuro * chf;
        break;

    case "AUD":
        newValue = userEuro * aud;
        break;

    case "CAD":
        newValue = userEuro * cad;
        break;
    default:
        Console.WriteLine("Invalid input!");
        break;
}
  • Related