82

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?

The Codesee
  • 3,714
  • 5
  • 38
  • 78
sharkin
  • 12,162
  • 24
  • 86
  • 122
  • Related question: http://stackoverflow.com/questions/1612584/update-struct-in-foreach-loop-in-c – AJ. Oct 23 '09 at 11:26
  • There is `foreach (ref var x in XXX)` syntax, available since C#7.3, when `Current` property of `Enumerator` returns `ref T` (e.g. for iteration on `Span`). See @Wolf's answer for details. – R2RT Nov 08 '21 at 14:43

10 Answers10

79

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."

Brian Rasmussen
  • 114,645
  • 34
  • 221
  • 317
  • 1
    This is true even for value types, i.e. structs. – technophile Oct 08 '09 at 14:50
  • 7
    @technophile: Actually you can't modify obj if MyClass is a struct, cause you're not allowed to modify the iteration variable itself. – Brian Rasmussen Oct 08 '09 at 14:57
  • @Brian Rasmussen: Why cant we modify the enumerable object ? – Amit Oct 09 '09 at 04:29
  • 2
    @Amy: According to the language specification (8.8.4) "The iteration variable corresponds to a read-only local variable with a scope that extends over the embedded statement." – Brian Rasmussen Oct 09 '09 at 06:21
  • public class MyClass { public int val; } class MyApp { public static void Main(String[] args) { IList list = new List(); MyClass obj1 = new MyClass(); obj1.val = 10; list.Add(obj1); MyClass obj2 = new MyClass(); obj2.val = 10; list.Add(obj2); foreach (MyClass obj in list) { obj.val = 20; } } } refer this code. This works ;) – Amit Oct 09 '09 at 08:38
  • @Amy: yes it does but you are not modifying obj itself, you're modifying what it points to. There's a difference. Try to set obj to null and you'll get the compile error. – Brian Rasmussen Oct 09 '09 at 09:01
  • Yes, you are right. It's giving compilation error.But it's quite strange. – Amit Oct 09 '09 at 14:16
  • @Amy: Not really. A value type variable stores the actual value. A reference type variable stores a reference to an object. It is the variable and not the referenced object that is read only and thus you can change the object via the reference, but you cannot change the reference itself. – Brian Rasmussen Oct 09 '09 at 14:28
  • @BrianRasmussen I'm just crazy and thought the question was phrased differently than it was. Sorry about that. – Servy Aug 22 '12 at 17:17
  • @technophile then why doesn't it work on my struct, but the bug is fixed when I change it to a class? See Deepfreezed's answer below. – Luc Feb 14 '13 at 08:39
  • I was incorrect about it working for structs; the compiler won't let you modify the iteration variable (including any of its fields) in that case. – technophile Feb 19 '13 at 17:17
23

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

jaccso
  • 336
  • 3
  • 6
22

You've asked 2 different questions here, lets take them in order.

Does a foreach loop iterate by reference?

If you mean in the same sense as a C++ for loop by reference, then no. C# does not have local variable references in the same sense as C++ and hence doesn't support this type of iteration.

Will the change be persisted

Assuming that MyClass is a reference type, the answer is yes. A class is a reference type in .Net and hence the iteration variable is a reference to the one variable, not a copy. This would not be true for a value type.

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
18

Well, it happened to me that my changes were not updated in a foreach loop when I iterated through var collection:

var players = this.GetAllPlayers();
foreach (Player player in players)
{
    player.Position = 1;
}

When I changed var to List it started working.

Community
  • 1
  • 1
mrzepa
  • 635
  • 7
  • 17
  • 1
    That's interesting. I wonder if the collection is cloned in such case. – sharkin Sep 05 '11 at 15:31
  • When using foreach... there are 2 cases. 1. It could cast to IEnumerable/IEnumerable if your class implements it. If your collection is a struct it will be boxed. 2. Using GetEnumerator() method directly. It's a method pattern of sorts. It allows for basic enumerators on value types without expensive boxing. IEnumerable is not required at all. But then, no linq of course (we need traits or some sort of value type interfaces). – Arek Bal Oct 07 '18 at 14:04
12

You can in this instance (using a List<T>) but if you were to be iterating over the generic IEnumerable<T> then it becomes dependant on its implementation.

If it was still a List<T> or T[] for instance, all would work as expected. The big gotcha comes when you are working with an IEnumerable<T> that was constructed using yield. In this case, you can no longer modify properties of T within an iteration and expect them to be present if you iterate the same IEnumerable<T> again.

helencrump
  • 1,351
  • 1
  • 18
  • 27
J Keegan
  • 121
  • 2
  • 5
8

Maybe it's interesting for you to lean that by version C# 7.3 it's possible to change values by reference provided that the enumerator's Current property returns a reference Type. The following would be valid (verbatim copy from the MS docs):

Span<int> storage = stackalloc int[10];
int num = 0;
foreach (ref int item in storage)
{
    item = num++;
}

Read more about this new feature at C# foreach statement | Microsoft Docs.

Wolf
  • 9,679
  • 7
  • 62
  • 108
4

this is true as long as it is not a struct.

Deepfreezed
  • 567
  • 2
  • 10
  • 18
  • 1
    Oh, that's good to know! Reading the top answers I was wondering why my code didn't work, but this explains it. Changed the struct to a class and \* *magic* \* it works. – Luc Feb 14 '13 at 08:37
2

Well, without understanding exactly what you mean by "Iterate by reference", I can't answer specifically yes or no, but I can say that what's going on under the surface is that the .net framework is constructing an "enumerator" class for each time client code calls a foreach, for the life of the foreach, that maintains a reference pointer into the collection being iterated over, and each time your foreach iterates, ir "delivers" one item and "increments" the pointer or reference in the enumerator to the next item...

This happens regardless of whether the items in the collection you are iterating over are values types or reference types.

Charles Bretana
  • 143,358
  • 22
  • 150
  • 216
0

obj is a reference to an item inside the List, hence if you change it's value it will persist. Now what you should be concerned about is whether or not get_the_list(); is making a deep copy of the List or returning the same instance.

Stan R.
  • 15,757
  • 4
  • 50
  • 58
  • 1
    It won't make a difference to the functionality he's interested in. Four copies of the same list will all reference the same actual objects, so whether you modify them from List1 or List3, either will result in the original object being modified. The only thing it will affect is if you add or remove items to/from the list, that wouldn't affect any copies of the list. – technophile Oct 08 '09 at 14:52
  • yes, the short answer of course is "yes, its a ref type", but the problems he might run into is if he it creates a copy of some original list, so if he calls get_the_list(); changes it and then calls get_the_list(); again somewhere else in the code, he might not get the results he expected. – Stan R. Oct 08 '09 at 14:55
0

Yes, that's also why you cannot alter the enumerable object in the context of the foreach statement.

Brian Scott
  • 9,221
  • 6
  • 47
  • 68