Consider this:
List obj_list = get_the_list();
foreach( MyClass obj in obj_list )
{
obj.property = 42;
}
Is obj
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.
this is true as long as it is not a struct.
You've asked 2 different questions here, lets take them in order.
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.
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.
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.