Why won't this simple subtraction work?
int MyPageNumber = Convert.ToInt32(cboPageNumber.SelectedItem);
MyPageNumber += (MyPageNumber - 1); //does not work
int MyNewPageNumber = MyPageNumber - 1; /works
I was also hoping someone could tell me why this gives me a "red line" for not being able to do a cast:
short MyPageNumber = Convert.ToInt16(cboPageNumber.SelectedItem);
MyPageNumber += MyPageNumber - ((short) 1); //does not work says can't cast
What am I not understanding? Is the + turning it into a String in the examples?
Thank you.
Look at exactly what this does:
MyPageNumber += (MyPageNumber - 1);
It adds MyPageNumber-1 to the existing value. So if MyPageNumber is 5, you end up with 9 instead of the 4 which you presumably want.
Now for the second problem, you've basically got a situation equivalent to this:
short x = 5;
short y = 10;
short z = x - y;
It looks okay, but C# doesn't actually have a subtraction operator for shorts - it only has it on ints, so it's implicitly converting both x
and y
to int
. The result is then an int
too, which you can't assign back to z
. You need:
short z = (short) (x - y);
(or the equivalent with your real variable names).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With