Differentiate between Foreach and For statement
I explain some situations where we should use Foreach or For. Foreach is better in term of performance but the object we got is read only, that means we cannot modify it. In some cases, we get the object from collection and make some modification during loop.
Consider 2 scripts of code:
Statement 1:
foreach( object A in collection)
{
int value = A.value;
A.value = 10;// Compiler error, since we cannot modify it.
}
Statement 2:
for(int i = 0; i < collection.Count; i++)
{
object A = collection[i];
A.value = 10;// Valid statement
}
In many cases, Statement 1 is the best choice.

Join the conversation! Your thoughts help the community grow.