Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mutability of the Enumerator struct

I have a problem with the following code:

  public static void RestoreToolStripMenuItem(ToolStripMenuItem item, List<string>.Enumerator enumerator )
    {
        item.Text = enumerator.Current;
        enumerator.MoveNext();

        if (item.HasDropDownItems)
        {
            var itemsWithoutSeparators = item.DropDownItems.OfType<ToolStripMenuItem>();
            foreach (var child in itemsWithoutSeparators)
            {
                RestoreToolStripMenuItem(child, enumerator);
            }
        }

}

After RestoreToolStripMenuItem is called recursively, enumerator is reseted (Current property points to the first element of the collection). It only can be get worked by passing enumerator by ref. I am wondering, why is this a case? Enumerator is a struct. What caused this problem, mutability of the Enumerator struct?

like image 264
Peter17 Avatar asked Dec 10 '25 13:12

Peter17


1 Answers

Yes, it's the changing state of the structure that causes that.

If you pass the structure by value, you would be using a copy of it in the method, and the one in the calling code would not change.

like image 124
Guffa Avatar answered Dec 12 '25 03:12

Guffa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!