Does foreach() iterate by reference?

前端 未结 10 1243
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-04 23:37

Consider this:

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

Is obj

相关标签:
10条回答
  • 2020-12-05 00:01

    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.

    0 讨论(0)
  • 2020-12-05 00:01

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

    0 讨论(0)
  • 2020-12-05 00:04

    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.

    0 讨论(0)
  • 2020-12-05 00:11

    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.

    0 讨论(0)
提交回复
热议问题