If I have a for loop like the following:
foreach(string email in installerEmails.Split(','))
{
Console.WriteLine(email);
}
Will the Split() call be made on each iteration of the loop? Do I need to store it in a temp array before iterating through it?
There is no foreach in C. You can use a for loop to loop through the data but the length needs to be know or the data needs to be terminated by a know value (eg. null).
You cannot make an infinite foreach loop. foreach is specifically for iterating through a collection. If that's not what you want, you should not be using foreach .
This foreach loop is faster because the local variable that stores the value of the element in the array is faster to access than an element in the array. The forloop is faster than the foreach loop if the array must only be accessed once per iteration.
C#'s foreach loop makes it easy to process a collection: there's no index variable, condition, or code to update the loop variable. Instead the loop variable is automatically set to the value of each element. That also means that there's no index variable with foreach .
No. It will iterate on the result of that call, i.e., the return type of Split
which is a string array: string[]
.
The result of Split is evaluated once, then GetEnumerator() is called on it. This returns an IEnumerator on which the MoveNext method and Current property is called in each iteration.
It's basically equivalent to:
string[] enumerable=installerEmails.Split(',');
IEnumerator<string> enumerator=enumerable.GetEnumerator();
while(enumerator.MoveNext())
{
string email=(string)enumerator.Current;
Console.WriteLine(email);
}
One ugly detail is the explicit cast to the type you give in the for loop the compiler generates. This was useful in C# 1.0 where IEnumerator wasn't generic.
I forgot that the Enumerator gets disposed. See Jon Hanna's answer for the code which includes dispose.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With