Does foreach() iterate by reference?

Viewed 58336

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?

10 Answers

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.

Related