Click here to Skip to main content
15,889,281 members
Please Sign up or sign in to vote.
1.67/5 (4 votes)
See more:
What is the difference between for and foreach loop. Which one is more convenient to use? Can you please explain it with example.
Posted
Comments
[no name] 19-Sep-13 6:39am    
Why are you unable to simply read the documentation?

It depends on what you are doing, and what you need.
If you are iterating through a collection of items, and do not care about the index values then foreach is more convenient, easier to write and safer: you can't get the number of items wrong.
If you need to process every second item in a collection for example, or process them ion the reverse order, then a for loop is the only practical way.

The biggest differences are that a foreach loop processes an instance of each element in a collection in turn, while a for loop can work with any data and is not restricted to collection elements alone. This means that a for loop can modify a collection - which is illegal and will cause an error in a foreach loop.

For more detail, see MSDN : foreach[^] and MSDN: for[^]
 
Share this answer
 
visit Here..

FOREACH Vs. FOR (C#)[^]
 
Share this answer
 
There is an article in CodeProject the Author of this article explains the difference between the Foreach and for loop. It might be also more helpful to get the clear picture of what is Foreach and for in detail.

FOREACH Vs. FOR (C#)[^]
 
Share this answer
 
Simple difference is :
in For each : you can print the key values.. You can use the key values of an array.
But in For : You cannot use or print the key values of an array
 
Share this answer
 
Comments
CHill60 7-Dec-14 12:55pm    
Wrong - you mean indices, not "key values". The question is over a year old and already adequately answered

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900