tags:

views:

136

answers:

5

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.

+5  A: 

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

Jon Skeet
thank you (everyone)
johnny
A: 

If MyPageNumber equals 3, the first equation would produce 5, the second would produce 2.

Also, you shouldn't need to cast a 1 to short ... the cast is unnecessary.

Jess
+1  A: 

Define "doesn't work" - seems fine to me... in particular:

int MyPageNumber = Convert.ToInt32("3");
MyPageNumber += (MyPageNumber - 1); // 5 as expected

Re the second; all short arithmetic results in an int, due to CPU efficiencies etc; try:

MyPageNumber += (short)(MyPageNumber - ((short)1));
Marc Gravell
A: 
MyPageNumber += (MyPageNumber - 1);

Means reduce MyPageNumber by one, then add the result of that to the old value of MyPageNumber.

For example if MypageNumber is 3:

3 += (3 - 1)
3 += 2
5

Ben S
A: 

You could do:

short magicNumber=1; MyPageNumber +=MyPageNumber-magicNumber;

You could also do

MyPageNumber += (short)(MyPageNumber-1);

See this MSDN Article

JoshBerke