Depends on what kind the list is.
If it’s a complex kind of list - class
- shall be by reference.
If it’s a primitive type list - string
, int
, bool
, decimals
, etc - will be by value. However, you cannot change the value of that variable because it is an iteration variable of the foreach
.
TL;DR;
This is due to the fact that primitive variables are allocated in memory other than complex types. There are two types of memory that you should worry about while developing:
- Memory Stack: Fast access memory and simple value allocation;
- Memory Heap: Not-so-fast access memory for complex value allocation;
When creating a primitive type variable - int, long, string, decimal, float, double, etc - this is addressed to an address in memory stack, and this address has allocated a value simple.
When an object is instantiated to a variable - new class();
- occurs as follows: the variable will reference an address in memory stack, but this address will reference is an address in memory heap, and that’s where all the values of your complex type will be.
See the image below:
When you make a foreach
in a complex type list, it occurs that a new variable is created in memory stack calling for item
this only has its reference changed to the list items. Thus, the foreach
is for reference.
But if it’s a primitive type list, that’s not possible, and you end up doing the foreach
for value.
I hope to have clarified everything in this question. If something else was missing, comment. :)
Simplifying
Make a loop like the one below:
foreach(var item in list)
{
/* aqui vai seu código */
}
IS almost what to do (this almost is relevant):
for(var i = 0; i < list.Length; i++)
{
var item = list[i];
/* aqui vai seu código */
}
But the foreach
is much more elegant. :)
Microsoft Documentation - foreach-in (C# Ference)
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/foreach-in
each time a loop is made, the variable
item
receives one of the items onlistItems
. I don’t quite understand your question– Italo Rodrigo
right @Italorodrigo but the information is received by Value or Reference?
– mcamara
I believe the list object reference is passed.
– user28595
Milton, it’s not always by value. It’s only by value if the list is a primitive type - see my answer. If it is a complex type list, it will be by reference.
– Thiago Lunardi
@It’s always worth it.
– Jéf Bueno
It is not by value, by value means a copy of the data, and it is not what happens.
– Thiago Lunardi