why does this produce compile-time error?
int [] a = new int[10];
foreach(int val in a)
{
val=0;
)
why does this produce compile-time error?
int [] a = new int[10];
foreach(int val in a)
{
val=0;
)
Because int is not a reference class.
foreach is for iterating through collections of reference objects.
Change it to a for loop instead.
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
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.
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.