Reputation: 31
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;
Upvotes: 3
Views: 6226
Reputation: 51224
Compiler detected that a path of execution exists in which the variable won't be assigned. If gr
is anything other than X
you will be using an unassigned value after the switch statement.
You can simply add the initial value to the declaration:
decimal sum = 0m;
Upvotes: 1
Reputation: 138
At declaration you should use this:
decimal sum=0m;
the compiler doesn't ensure that the first case will hold so sum may still be used without assigning
Upvotes: 0
Reputation: 66388
Simply assign default value to it when declaring and you won't get error:
decimal sum = 0;
Upvotes: 0
Reputation: 4998
This is because the variable sum is only assigned if the switch statement hits the "X" case. To fix this, set a default value by doing the following at the top:
decimal sum = 0m;
Upvotes: 1
Reputation: 18488
Only instance variables
get default values, so a local variable like sum
, has to be initialized
, for it to be used somewhere else. Since there is the possibility that it will not get assigned anything, the compiler raises an error.
Upvotes: 3
Reputation: 50682
If gr
is NOT equal to "X" sum
has no value. The compiler is warning you for that.
Upvotes: 7
Reputation: 9356
You are only setting the value of sum for ONE condition and hence it won't always be assigned at the point when you are trying to convert it to string. Try declaring it as decimal sum = 0.0;
.
Upvotes: 1