0

I have a List<string>, which contains payrollnumbers as strings, e.g.:

 List<string> payrollnumbers = new List<string>() { "0","1","3" };

I want to get the next value in the list, so:

  • if currpayrollnumber is 0, I want to get the value 1,
  • if currpayrollnumber is 1, I want to get the value 3,
  • etc.

I have the following code, however it does not work like expected:

 List<string> payrollnumbers = new List<string>();
 // fill payrollnumbers ...
 var currpayrollIndex = payrollnumbers.IndexOf(currpayrollnumber);
 var nextPayrollIndex = currpayrollIndex++;
 var payrollnumber = payrollnumbers[nextPayrollIndex];
mcserep
  • 3,231
  • 21
  • 36
DangerCoder
  • 71
  • 2
  • 9

3 Answers3

2

Because you are using the postfix increment operator (i++) the original value is what gets assigned to nextPayrollIndex before currpayrollIndex is incremented. You could use the prefix increment operator (++i) instead, but I would suggest either making it explicit that you are adding 1 and not increment currpayrollIndex at all.

var nextPayrollIndex = currpayrollIndex + 1;

Or just increment currpayrollIndex and use it instead of nextPayrollIndex.

currpayrollIndex++;
var payrollnumber = payrollnumbers[currpayrollIndex];

I'd also suggest adding checks for when the currpayrollnumber is not in the list (IndexOf will return -1) and when it's the last item (to avoid an ArgumentOutOfRangeException)

juharr
  • 31,741
  • 4
  • 58
  • 93
1

All you need to do is use ++currpayrollIndex instead of currpayrollIndex++:

var nextPayrollIndex = ++currpayrollIndex;

You can also remove that line entirely and put it in when you access the array:

var payrollnumber = payrollnumbers[++currpayrollIndex];

However it's very unreadable, and might not be noticed by people skimming over the code

Shadow
  • 3,926
  • 5
  • 20
  • 41
1

You have to change:

 var nextPayrollIndex = currpayrollIndex++;

to

var nextPayrollIndex = ++currpayrollIndex;

Is Your solution currpayrollIndex value is increase by 1 after assign to nextPayrollIndex variable

When You change the moment of increase currpayrollIndex by 1 - You first increase by 1 currpayrollIndex value and next assign to nextPayrollIndex variable

It is good explanation here:

What is the difference between i++ and ++i?

Also You may want to change You code to this:

var currpayrollIndex = payrollnumbers.IndexOf(currpayrollnumber);
var payrollnumber = payrollnumbers[++currpayrollIndex ];

it will by more readable

Community
  • 1
  • 1
blogprogramisty.net
  • 1,714
  • 1
  • 18
  • 22