Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does foreach() iterate by reference?

Consider this:

List<MyClass> obj_list = get_the_list(); foreach( MyClass obj in obj_list ) {     obj.property = 42; } 

Is obj a reference to the corresponding object within the list so that when I change the property the change will persist in the object instance once constructed somewhere?

like image 436
sharkin Avatar asked Oct 08 '09 14:10

sharkin


People also ask

How does a foreach loop work?

How Does It Work? The foreach loop in C# uses the 'in' keyword to iterate over the iterable item. The in keyword selects an item from the collection for the iteration and stores it in a variable called the loop variable, and the value of the loop variable changes in every iteration.

Is PHP foreach by reference?

This is an example why pass-by-reference in foreach loops is BAD. This is because when the second loop executes, $entry is still a reference. Thus, with each iteration the original reference is overwritten.

Which is better for loop or foreach?

This foreach loop is faster because the local variable that stores the value of the element in the array is faster to access than an element in the array. The forloop is faster than the foreach loop if the array must only be accessed once per iteration.

Does foreach work with lists?

Using the CodeThe ForEach method of the List<T> (not IList<T> ) executes an operation for every object which is stored in the list. Normally it contains code to either read or modify every object which is in the list or to do something with list itself for every object.


2 Answers

Yes, obj is a reference to the current object in the collection (assuming MyClass is in fact a class). If you change any properties via the reference, you're changing the object, just like you would expect.

Be aware however, that you cannot change the variable obj itself as it is the iteration variable. You'll get a compile error if you try. That means that you can't null it and if you're iterating value types, you can't modify any members as that would be changing the value.

The C# language specification states (8.8.4)

"The iteration variable corresponds to a read-only local variable with a scope that extends over the embedded statement."

like image 91
Brian Rasmussen Avatar answered Sep 20 '22 05:09

Brian Rasmussen


Yes, until you change the generic type from List to IEnumerable..

like image 30
jaccso Avatar answered Sep 22 '22 05:09

jaccso