Cannot assign to 'obj' because it is a 'foreach iteration variable'

I asked during a job interview is there a difference between for to foreach are not in terms of performance in terms of working with objects. Can I update the same set of both?
Desalination to see which candidate did not know the answer.
I'm not going to explain who was stronger for or foreach.
That you can read the article by Dustin Campbell - Performance of foreach vs. List.ForEach.
So I'll give a practical example, explain the difference from for to foreach when both cases I'm going to update my system.

Here's the code for example:
Is for or/and  foreach will update the List?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace CheckFor
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> arr = new List<string>();
            arr.Add("aaa");
            arr.Add("bbb");
            arr.Add("ccc");
            arr.Add("ddd");
            arr.Add("eee");
            arr.Add("fff");
            for (int i = 0; i < arr.Count; i++)
            {
                arr[i] = arr[i].ToString() + arr[i].ToString();
            }
            foreach (string obj in arr)
            {
                obj = obj + obj;
            }
        }
    }
} 

Then there are those straight to see a foreach loop can not update items because it actually makes a copy for collection, while a for loop can update the objects because it really is on the objects.

Again, I'm not going to explain what it means by value and by reference.
But if you meet the following message - remember the meaning of objects update

Cannot assign to 'Your object' because it is a 'foreach iteration variable'

Example of the error

Cannot assign to 'obj' because it is a 'foreach iteration variable'

Yours,
Roi

Comments

Popular posts from this blog

A sharepoint list view of the current month

The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters

Export SharePoint 2010 List to Excel with PowerShell