Modifying objects with foreach

This is basically a theoretical question: I do not need a practical solution, but when used foreachin MS V C # 2010 with the following code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            int[] ints = new int[7]{0,0,0,0,0,0,0};
           foreach (int i in ints)
           {
                i = 10;

           }
           Console.ReadKey();
        }
    }
}

I get an error that tells me that I cannot change i because it is a variable foreach, now if I wanted to be able to do this simple task in several other ways, but the fact is that I did not see anything in the documentation , which would forbid what I am trying to do, and I think it foreachshould give you the opportunity to change the variable in the list.

Is there something I am missing?

+3
source share
2 answers

Use the for loop instead and change the values ​​with ints [i]

+2
source

If you are foreachabove the collection, you will receive items as read-only. If you change the loop to a traditional loop for, you can change the contents of the array:

  for (int index = 0; index < ints.Length; ++index)
  {
      ints[index] = 10;
  }
+6
source

All Articles