Hello all,
I have a list of data that I iterate through ++ or — depending on a users input. When I get to 0 or the end I have a if statement (if value == 0, iterator = value.count || if value == value.count, interator = 0)
Anyhow, my code works and all, but I am wondering if there is an automatic way where this is handled for me?
Thanks!
Not sure what you mean by ‘automatic’, but a slightly prettier way could be to just wrap the iteration in a while loop.
I’d create my own RollingCollection
kind of type that encapsulates List<T>
or T[]
, implements IEnumerable
and handles the index being out of bounds and its reset inside of the MoveNext()
method.
Although, since you also seem to want to use negative indexes, so that arr[-12]
when arr
has 10 elements would roll back to arr[8]
, you’d probably need to implement a custom Get(int index)
method that would calculate the “safe” index when the given one is out of bounds.
Although, at this point, I guess you can just write an extension method like GetWithRollover(int index)
for a generic List<T>
.
C# devs
null reference exceptions