Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I declare a variable in C# and cannot use it inside of the switch statement

Consider this C# code:

string gr = comboBox1.ValueMember;
decimal sum;
try
{
    decimal rite = Convert.ToDecimal(textBox1.Text);
    decimal left = Convert.ToDecimal(textBox2.Text);
}
catch (Exception)
{
    string swr = "Please enter REAL a number, can be with decimals";
    label2.Text = swr;
}

switch (gr)
{
    case "X":
        sum = 12M;
        break;
    case "/":
        break;
    case "*":
        break;
    case "-":
        break;
    default:
        break;
}

answerText.Text = Convert.ToString(sum);

If I give the decimal sum a value during the switch statement, it will popup with an error statement saying:

Use of unassigned local variable 'sum'

I'm a newbie at C# so this might sound stupid saying it. It looks like I ALREADY set the value of sum inside the switch statement. I tried putting the same sum = 12M; in all of the other case statements, but that doesn't seem to help.

By the way, im also having problems modifying other variables outside of the switch statement - EX. rite, left;

like image 531
Jonathan Leigh Avatar asked Jan 25 '26 06:01

Jonathan Leigh


1 Answers

If gr is NOT equal to "X" sum has no value. The compiler is warning you for that.

like image 101
Emond Avatar answered Jan 27 '26 18:01

Emond



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!