Azurewrath

Hi all,

In this code, am I right to assume that split will be called for each element foreach iterates, like:

split

access subString

split

access subString

...

foreach ( string subString in s1.Split( delimiters ) )
{
output += ctr++;
output += ": ";
output += subString;
output += "\n";
}

I use a language that works this way, so I thought if that's the case with this

The other alternative I think is creating a variable holding the splitted string, so it doesn't call the split method each time.

Thanks,

aw



Re: Visual C# Language foreach question

sthotakura

It splits before starting the execution of foreach statement, but not every time

Cheers,

Suresh





Re: Visual C# Language foreach question

Paresh_Sen_3889e7

is it changing the string into a collection in the very first loop



Re: Visual C# Language foreach question

nielsvanvliet

>is it changing the string into a collection in the very first loop

Strings are immutable, so, no, it does not change the string.
It returns a new array of strings. And an array is IEnumerable, so you can iterate on it using foreach.

Note (do not read it if you are confused): in case there is no split (i.e, the string does not contain the separator), the string inside the array can be the string that is split (i.e. reference equal).
Regards




Re: Visual C# Language foreach question

Azurewrath

Thanks for the replies. So can I say foreach statement is evaluated only once, unlike the for loop's condition statement

Thanks,

aw





Re: Visual C# Language foreach question

Paresh_Sen_3889e7

Thanks Niels.



Re: Visual C# Language foreach question

nielsvanvliet

>Thanks for the replies. So can I say foreach statement is evaluated only once, unlike the for loop's condition statement

Yes. If you want to better understand the cost of IEnumerable, you should write one yourself, and use debug to see what is called.

You can use the section Implementing IEnumerator (do not forget the sectuiib 'C# 2.0 to the Rescue' which simplify A LOT the code).

http://www.ondotnet.com/pub/a/dotnet/2004/06/07/liberty.html






Re: Visual C# Language foreach question

Azurewrath

Thanks Niels, very helpful!

aw