C # Difference between Foreach and for (not performance)


Some time ago I read that foreach works with "copies" of objects and, therefore, can be used to extract information, and not to update it. I do not understand, since it is quite possible to scroll through the list of classes and change its field. Thank!

+5
source share
5 answers

What you may have read is that you cannot change the collection when repeated with foreach, while you can (if you are careful) use a loop for. For instance:

using System;
using System.Collections.Generic;

class Test
{
    static void Main()
    {
        var list = new List<int> { 1, 4, 5, 6, 9, 10 };


        /* This version fails with an InvalidOperationException
        foreach (int x in list)
        {
            if (x < 5)
            {
                list.Add(100);
            }
            Console.WriteLine(x);
        }
         */

        // This version is okay
        for (int i = 0; i < list.Count; i++)
        {
            int x = list[i];
            if (x < 5)
            {
                list.Add(100);
            }
            Console.WriteLine(x);            
        }
    }
}

, , - , , , .

+9

foreach:

var list = new List<string>();
list.AddRange(new string[] { "A", "B", "C" });

foreach (var i in list)
{
    // compilation error: Cannot assign 'i' because it is a 'foreach iteration variable'
    i = "X";
}

for , , .

+1

foreach Iterator . Anything, IEnumerable. IEnumerable ( 0 1 2 3 4... 1000...) IEnumerable.

for - #, ( , )

, Iterator .NET .

+1

foreach IEnumerable . (, ), , .

for - . .

+1

readonly:

private readonly List<int> MyList = new List<int>();

MyList = new List<int>(), , MyList, , MyList.Add(3).

, , foreach, :

foreach(List<int> lst in MyListOfLists)
{
  lst = new List<int>(); // not allowed
  lst.Add(3);  // allowed
}

, , foreach, , :

foreach(int x in SomeEnumerable)
{
    if(x != 0)
        SomeEnumerable.Add(0);
}

, Add SomeEnumerable, , " . , .

0

All Articles