What is the main use of foreach in C# . Instead of using simple for loop. Is all .Net frame work support foreach.
2 Answers
Know the answer? Post it. Somebody with the same question will find it here.
pratik patel7 reputationPosted Apr 9, 2014, 3:37 AM EDT
0
The foreach loop in C# executes a block of code on each element in an array or a collection of items. When executing foreach loop it traversing items in a collection or an array . The foreach loop is useful for traversing each items in an array or a collection of items and displayed one by one.
Code
foreach(variable type in collection){
// code block
}
Code
variable type : The variable used for collect the item from Collection
collection : Collection of items
C#
string[] days = { "Sunday", "Monday", "TuesDay"}; foreach (string day in days) { MessageBox.Show("The day is : " + day); }
The above C# example first declared a string array 'days' and initialize the days in a week to that array. In the foreach loop declare a string 'day' and pull out the values from the array one by one and displayed it.
pratik patel7 reputationPosted Apr 9, 2014, 3:37 AM EDT
The foreach loop in C# executes a block of code on each element in an array or a collection of items. When executing foreach loop it traversing items in a collection or an array . The foreach loop is useful for traversing each items in an array or a collection of items and displayed one by one.
string[] days = { "Sunday", "Monday", "TuesDay"}; foreach (string day in days) { MessageBox.Show("The day is : " + day); }The above C# example first declared a string array 'days' and initialize the days in a week to that array. In the foreach loop declare a string 'day' and pull out the values from the array one by one and displayed it.
using System; using System.Windows.Forms; namespace WindowsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { string[] days = { "Sunday", "Monday", "TuesDay", "Wednesday", "Thursday", "Friday", "Saturday" }; foreach (string day in days) { MessageBox.Show("The day is : " + day); } } } }Munesh SharmaRank #174 · 13.9K reputationPosted Apr 9, 2014, 3:47 AM EDT
For Loop:
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questionsTop experts