Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple subtraction and cast question

Tags:

c#

casting

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.

like image 673
johnny Avatar asked Sep 18 '25 17:09

johnny


1 Answers

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

like image 159
Jon Skeet Avatar answered Sep 21 '25 06:09

Jon Skeet