0

I'm trying to enumerate values of List in different methods (just to send iterator as an argument). It works well, but to my surprise, it's indexes value reset to 1 after it exit the method. Here is an example - can you explain to me how it works and how to solve it?

Thank you so much!

public void SaveHistory(string folder)
{
    using (var iterator = Items.GetEnumerator())
    {
        foreach (var file in _files)
            if (!Proceed(Path.Combine(folder, file.Name), iterator)) //first call
                break;
            //AND HERE my iterator.Index value is 1 again.
        while (Proceed(GetNewFileName(folder), iterator)) { }
     }
}
private bool Proceed(string fileName, IEnumerator<HistoryItemBase> iterator)
{
    var dose = new List<HistoryItemBase>();
    if (iterator.MoveNext())
    {
        while (dose.Count < LogFileItemsCount && iterator.MoveNext())
            dose.Add(iterator.Current);
        //DO Something
    }
    return false; //<- Here iterator.MoveNext() returns false and it's index value is ok
}
Clemens
  • 123,504
  • 12
  • 155
  • 268
Artem Makarov
  • 874
  • 3
  • 14
  • 25
  • 4
    [It's a struct](http://stackoverflow.com/questions/3168311/why-do-bcl-collections-use-struct-enumerators-not-classes), [pass it by reference](http://stackoverflow.com/questions/16614704/pass-c-sharp-struct-by-reference) or consider a different design that doesn't require passing around an enumerator altogether. – CodeCaster Mar 06 '16 at 22:15
  • Yep.. understand it only after asking a question.. It's a bad idea to work till night :) But thank you so much for your answer! – Artem Makarov Mar 07 '16 at 08:00

1 Answers1

0

Well, the answer is very easy - in my case iterator is a struct and all structs passes to methods by value, not reference.. And in my case I can't just add a ref word to a parameter, because I'm working with using- statement.

Thank you!

Artem Makarov
  • 874
  • 3
  • 14
  • 25