Is it possible to: increment index by 1 and wrap back to 0 if(index > list.Count) within 1 line of code?

What I'm doing right now:

index++;
index %= list.Count;

I want to merge them into 1 quick line, something like:

++index %= list.Count;

But the compiler is not allowing me to.

I would love to know:

  1. Is it possible to merge those 2 into 1 quick, easy-to-read line?
  2. Explanation why what I'm doing doesn't work, IIRC I used to do that all the time in C/C++

Thanks for your time!

Jon Skeet
people
quotationmark

I'd be slightly surprised if the first version worked in C or C++, but then it does surprise me quite often. The reason it doesn't work in C# is that the left-hand side of the %= operator has to be a variable, and the expression ++index isn't classified as a variable - it's a value.

I wouldn't call it an "easy to read" line anyway though. What is pretty simple to understand is this:

index = (index + 1) % list.Count;

No need for a compound assignment operator at all.

people

See more on this question at Stackoverflow