0

On another page I've said that nr = 0

var number = this.NavigationContext.QueryString["nr"];
int Nr = Convert.ToInt16(number);

And this works, Nr = 0

Now I want to upgrade Nr by one:

int next = Nr++;

Unfortunately this doesn't work... next = 0 too, but it supposed to be 1.

Could someone explain to me what I'm doing wrong?

4 Answers4

8

Nr++ increments and returns the original value of Nr.

++Nr increments and returns the new value of Nr. So what you want is:

int next = ++Nr;
Mike Christensen
  • 88,082
  • 50
  • 208
  • 326
3

In C# (or C++), the statement

int next = Nr++;

translates to, "assign the value of Nr to variable next, and then increment Nr by 1.

If you want Nr to increment first, your statement should look like this:

int next = ++Nr;

Here is the definition of the ++ operator: http://msdn.microsoft.com/en-us/library/36x43w8w.aspx

Nathan A
  • 11,059
  • 4
  • 47
  • 63
0

the problem is ...Nr is incremented after Nr set to next use next=Nr+1;

HackerMan
  • 904
  • 7
  • 11
0

There are two increment operators - pre-increment ++c and post-increment c++.

var x = ++c; is equivalent to

c = c + 1;
var x = c;

while var x = c++; is equivalent to

var x = c;
c = c + 1;

and therefore x either receives the value before or after c got incremented.

Daniel Brückner
  • 59,031
  • 16
  • 99
  • 143