Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will this foreach loop call Split() each iteration in C#?

Tags:

c#

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?

like image 686
FrankTheBoss Avatar asked Oct 14 '10 14:10

FrankTheBoss


People also ask

What is foreach loop in C?

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).

Is foreach loop infinite?

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 .

Which loop is better for or 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.

Can we obtain the array index using foreach loop in C #?

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 .


2 Answers

No. It will iterate on the result of that call, i.e., the return type of Split which is a string array: string[].

like image 53
Ahmad Mageed Avatar answered Sep 30 '22 02:09

Ahmad Mageed


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.

like image 5
CodesInChaos Avatar answered Sep 30 '22 01:09

CodesInChaos