The current index in the foreach
-
Just a quickie for many thanks; In a for loop I can get my current index quit easy;
for (int i=0; i<8; ++i) Console.WriteLine("Current index = "+i);
But with a foreach statement it's different. I only know this ugly way;int i=0; foreach (int curInt in intCollection) { Console.WriteLine("Current index = "+i); i++; }
Maybe I'm asking the impossible because foreach is for collections so it doesn't have a strict index. But Maybe there's an index keyword? Couldn't find it at the MSDN C# site. -
Just a quickie for many thanks; In a for loop I can get my current index quit easy;
for (int i=0; i<8; ++i) Console.WriteLine("Current index = "+i);
But with a foreach statement it's different. I only know this ugly way;int i=0; foreach (int curInt in intCollection) { Console.WriteLine("Current index = "+i); i++; }
Maybe I'm asking the impossible because foreach is for collections so it doesn't have a strict index. But Maybe there's an index keyword? Couldn't find it at the MSDN C# site.And you won't find any. The ugly way is the only way to do it. "God doesn't play dice" - Albert Einstein "God not only plays dice, He sometimes throws the dices where they cannot be seen" - Niels Bohr
-
And you won't find any. The ugly way is the only way to do it. "God doesn't play dice" - Albert Einstein "God not only plays dice, He sometimes throws the dices where they cannot be seen" - Niels Bohr
-
Ow well that's to bad. Is there any reason to use a foreach instead off a for loop? My objections for using a foreach are; - 'Ugly' indexing, as stated above - Collection can't be modified while foreach-ing the collection.
Use a for loop if you need indexing. Use foreach if you don't need indexing and you like syntax candy.
Tech, life, family, faith: Give me a visit. I'm currently blogging about: Homosexuality in Christianity Judah Himango
-
Ow well that's to bad. Is there any reason to use a foreach instead off a for loop? My objections for using a foreach are; - 'Ugly' indexing, as stated above - Collection can't be modified while foreach-ing the collection.
foreach
is great when you're abstracting your code. Indexing is purely for lists, and if you're doing a foreach on anIEnumerable
, then you're always sure to get the maximum performance. Consider the performance issues on indexing eg. a linked list or a binary tree. I'm always declaring my collection member variables as the lowest denominator. Eg. if I need a map, then I'm declaring anIDictionary
, and when I'm iterating through the elements, I'll use a foreach loop. This means that if I am to use a counter, then I have to do it the ugly way. "God doesn't play dice" - Albert Einstein "God not only plays dice, He sometimes throws the dices where they cannot be seen" - Niels Bohr -
foreach
is great when you're abstracting your code. Indexing is purely for lists, and if you're doing a foreach on anIEnumerable
, then you're always sure to get the maximum performance. Consider the performance issues on indexing eg. a linked list or a binary tree. I'm always declaring my collection member variables as the lowest denominator. Eg. if I need a map, then I'm declaring anIDictionary
, and when I'm iterating through the elements, I'll use a foreach loop. This means that if I am to use a counter, then I have to do it the ugly way. "God doesn't play dice" - Albert Einstein "God not only plays dice, He sometimes throws the dices where they cannot be seen" - Niels BohrYou can use IndexOf property of the collection you use, but since you're using foreach, there's no reason to think about indexes.
-
Use a for loop if you need indexing. Use foreach if you don't need indexing and you like syntax candy.
Tech, life, family, faith: Give me a visit. I'm currently blogging about: Homosexuality in Christianity Judah Himango
It isn't about whether you "like syntax candy," it is about whether you like writing quality code. See Jan Larsen's reply for more insight. Matt Gerrans
-
It isn't about whether you "like syntax candy," it is about whether you like writing quality code. See Jan Larsen's reply for more insight. Matt Gerrans
I'm not against using foreach, I use it quite a lot in my code. I just don't agree that 'foreach' is quality where 'for' is not. Both are easily recognizable by any novice programmer. As I said to the origin poster, if you need an index, you might as well be using for instead of foreach. The IEnumerable idea is cool, and gets even better with C# 2.0's iterators with the yield keyword (allowing you to, basically, write co-routines). Coupled with foreach, it is really great. That doesn't mean we should never use the 'for' keyword. My 'syntax candy' statement wasn't meant to belittle IEnumerable or foreach keyword; I'm merely saying that it is a simple syntax expression that does a lot under the hood (initialize an Enumerator, call the appropriate method calls each loop, and return the next object in the enumeration). You could call your own GetNext() and other appropriate IEnumerator functions yourself, 'foreach' is syntax candy that allows you to forgo typing all that.
Tech, life, family, faith: Give me a visit. I'm currently blogging about: Homosexuality in Christianity Judah Himango
-
You can use IndexOf property of the collection you use, but since you're using foreach, there's no reason to think about indexes.
ltinka wrote: You can use IndexOf property of the collection you use Well, not really since there is no definite index in a map. Talking lists I definately agree, in a linked list, IndexOf() would trigger a reiteration, so it would have been better to use indexing in the first place. "God doesn't play dice" - Albert Einstein "God not only plays dice, He sometimes throws the dices where they cannot be seen" - Niels Bohr
-
I'm not against using foreach, I use it quite a lot in my code. I just don't agree that 'foreach' is quality where 'for' is not. Both are easily recognizable by any novice programmer. As I said to the origin poster, if you need an index, you might as well be using for instead of foreach. The IEnumerable idea is cool, and gets even better with C# 2.0's iterators with the yield keyword (allowing you to, basically, write co-routines). Coupled with foreach, it is really great. That doesn't mean we should never use the 'for' keyword. My 'syntax candy' statement wasn't meant to belittle IEnumerable or foreach keyword; I'm merely saying that it is a simple syntax expression that does a lot under the hood (initialize an Enumerator, call the appropriate method calls each loop, and return the next object in the enumeration). You could call your own GetNext() and other appropriate IEnumerator functions yourself, 'foreach' is syntax candy that allows you to forgo typing all that.
Tech, life, family, faith: Give me a visit. I'm currently blogging about: Homosexuality in Christianity Judah Himango
Judah Himango wrote: My 'syntax candy' statement wasn't meant to belittle IEnumerable or foreach keyword; I'm merely saying that it is a simple syntax expression that does a lot under the hood (initialize an Enumerator, call the appropriate method calls each loop, and return the next object in the enumeration). You could call your own GetNext() and other appropriate IEnumerator functions yourself, 'foreach' is syntax candy that allows you to forgo typing all that. Basically, that's what high level languages are all about :-), I've done my share of Java programming, and I can assure you that I don't miss this:
for (Iterator i = myList.iterator(); i.hasNext();)
{
String tmp = (String) i.next();
}I'd rather do this:
foreach(String tmp in myList)
{
}Eye candy maybe, but much clearer, and I guess the ease of use, has got more inexperienced programmers to use the correct iterating technique. I'm not joking, I've had colleques that would use this on a linked list:
for (int i = 0; i < myList.size(); i++)
{
String tmp = (String) myList.get(i);
}"God doesn't play dice" - Albert Einstein "God not only plays dice, He sometimes throws the dices where they cannot be seen" - Niels Bohr
-
Ow well that's to bad. Is there any reason to use a foreach instead off a for loop? My objections for using a foreach are; - 'Ugly' indexing, as stated above - Collection can't be modified while foreach-ing the collection.
cazzz wrote: Is there any reason to use a foreach instead off a for loop? Using foreach will automatically cast an item in the collection to right type. Example:
for (int i = 0; i < 8; ++i)
{
// You need to cast.
Customer cust = (Customer)customers[i];
}instead
foreach (Customer cust in customers)
{
// cust is now of correct type Customer.
}Use foreach when you just want to iterate over all items and don't care about order or which item is the current item. Handle special behaviour inside a class and not in the calling code according to classic OO principles. Example:
// Calling code somehow knows that customers[4] needs some special handling.
for (int i = 0; i < 8; ++i)
{
if (i == 4)
{
Customer cust = (Customer)customers[i];
DoSumthingWithCustomer(cust);
}
}instead
// Calling code only knows it needs to call a method for each customer object.
foreach (Customer cust in customers)
{
// cust is now of correct type Customer.
cust.DoSumthing();
}You should implement the class Customer so when calling method DoSumthing() on its objects it will only do something for the object which have index 4 in the for loop. Ugly indexing is normally not needed in my experience. /Patric My C# blog: C# Coach
-
cazzz wrote: Is there any reason to use a foreach instead off a for loop? Using foreach will automatically cast an item in the collection to right type. Example:
for (int i = 0; i < 8; ++i)
{
// You need to cast.
Customer cust = (Customer)customers[i];
}instead
foreach (Customer cust in customers)
{
// cust is now of correct type Customer.
}Use foreach when you just want to iterate over all items and don't care about order or which item is the current item. Handle special behaviour inside a class and not in the calling code according to classic OO principles. Example:
// Calling code somehow knows that customers[4] needs some special handling.
for (int i = 0; i < 8; ++i)
{
if (i == 4)
{
Customer cust = (Customer)customers[i];
DoSumthingWithCustomer(cust);
}
}instead
// Calling code only knows it needs to call a method for each customer object.
foreach (Customer cust in customers)
{
// cust is now of correct type Customer.
cust.DoSumthing();
}You should implement the class Customer so when calling method DoSumthing() on its objects it will only do something for the object which have index 4 in the for loop. Ugly indexing is normally not needed in my experience. /Patric My C# blog: C# Coach
Patric_J wrote: Ugly indexing is normally not needed in my experience. I beg to differ. More often than not these days, I find myself writing stuff like this:
protected void DoSomething(MySortedStringList sortedElements, string[] buffer)
{
int i = 0;
foreach (string element in sortedElements)
{
buffer[i++] = element;
}}
But that's what happens when having Hashtable as favourite collection :rolleyes: "God doesn't play dice" - Albert Einstein "God not only plays dice, He sometimes throws the dices where they cannot be seen" - Niels Bohr