Monday, April 8, 2013

foreach is pass by reference

To find out foreach iteration is pass by reference or pass by value, I wrote the test code as following:
        private static void test()
        {
            List<DataRecord> strlist = new List<DataRecord>(10);
            for (int i = 0; i < 10; i++)
                strlist.Add(new DataRecord(new String[] { }));
            int k=0;
            foreach (DataRecord r in strlist)
            {
                r["test"] = k++;
            }
            foreach (DataRecord r in strlist)
                Debug.Write(r["test"] + " ");
        }
And the result is:
 0 1 2 3 4 5 6 7 8 9 
So the conclusion is that foreeach iteration is pass by reference. Another interesting point is that if use something like foreach(string s in strlist), you cannot change the value of the string

No comments:

Post a Comment