0

why does this produce compile-time error?

int [] a = new int[10];
foreach(int val in a)
{
     val=0;
)
4
Contributors
3
Replies
4
Views
6 Years
Discussion Span
Last Post by Momerath
0

Because int is not a reference class.
foreach is for iterating through collections of reference objects.
Change it to a for loop instead.

Votes + Comments
exactly the problem
0

Try something like:

int[] a = new int[10];
            for (int i = 0; i < a.Length; i++)
            {
                a[i] = 1;
            }

Worth noting; the above does highlight why using meaningless variable names for anything more than loops (and sometimes even for those) is a bad idea :p

0

foreach is used to iterate through any collection that implements the IEnumerable interface (which includes arrays of value types). But, the foreach iteration variable (in your case val) cannot be assigned to as this would 'break' the enumeration that was obtained. You also cannot alter the collection that is being iterated through (in your case, the a variable) by adding or deleting any elements. Again, this breaks the enumeration.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.