-3
int price;

    if (listBox1.Text == "Regular McYum")   
        {
           price = 70;
        }

How come the 'price' variable is assigned but never used?

AJ Gayeta
  • 73
  • 7

2 Answers2

0

The warning is just clear: assigning a variable and using it are different things. The first is you set a value to it, the second ones means you´re doing something with that value.

So in your case you should pass your variable to a method for example:

Console.WriteLine(price);

This should be a warning from your compiler, so you can - although you shouldn´t - ignore this.

MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111
-1

If listBox1.Text does not equal "Regular McYum", then price will never get set. You need to ensure that price will receive a value on all of the possible code paths.

J. Perkins
  • 4,156
  • 2
  • 34
  • 48
  • It will default to 0 and that has nothing to do with the fact that it's never used, which means the value is read not written. `price = 70;` is not a use, it's an assignment. – juharr Jun 02 '17 at 14:25
  • That's not what the warning is saying. The warning is saying that `price` is given a value (`price = 70;`) but the code does nothing with that value. It's similar to a completely un-used variable, except there is an assignment performed. – sab669 Jun 02 '17 at 14:26