开发者

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;


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


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.


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;.


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;


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;


Simply assign default value to it when declaring and you won't get error:

decimal sum = 0;


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜