It depends on the type of the list.
If it is a complex type list - class
- will be by reference.
If it is a list of primitive type - string
, int
, bool
, decimals
, etc - will be by value. However, you can not change the value of this variable, because it is an iteration variable of foreach
.
TL; DR;
This is due to the fact that, primitive variables are allocated in memory different from complex types. There are two types of memory that you should worry about as you develop:
-
Stack memory : Fast access memory and simple value allocation;
-
Heap memory : Not so fast access memory for complex value allocation;
When you create a primitive type variable - int, long, string, decimal, float, double, etc - this is addressed to an address in stack , and that address has a < strong> value simple.
When you instantiate an object to a variable - new class();
- the following occurs: the variable will reference an address in stack , but this address will < strong> to an address in heap memory, and that's where all the values of your complex type will be.
See the image below:
Whenyoumakea
foreach
inalistofcomplextype,ithappensthatanewvariableiscreatedinmemorystackcalled
item
thatonlyhasitsreferencechangedforthelistitems.Therefore,
foreach
isbyreference.
Butifitisalistofprimitivetype,thisisnotpossible,andyouendupdoingforeach
forvalue.
IhopeIhaveclarifiedeverythingonthisissue.Ifsomethingelsewasmissing,comment.:)
Simplification
Loopasbelow:
foreach(variteminlist){/*aquivaiseucódigo*/}
Italmostisthesameasdoing(thisalmostisrelevant):
for(vari=0;i<list.Length;i++){varitem=list[i];/*aquivaiseucódigo*/}
Butforeach
ismuchmoreelegant.:)
MicrosoftDocumentation-foreach-in(C#reference)
link