Getsuyodev, Programming is mainly used when constructing an application. Programming requires knowledge of application domains, algorithms, and programming language expertise. Programming can be developed in different logic based on developer knowledge.

How to use C# foreach loop



The foreach loop in C# executes a block of code on each element in an array or a collection of items. When executing the foreach loop, it traversing items in a collection or an array. The foreach loop is useful for traversing each item in an array or a collection of items and displayed one by one.

foreach(variable type in collection){
  // code block
}
variable type : The variable used for collect the item from Collection
collection	  : Collection of items
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 initialized 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);
            }
        }
    }
}

Comments are closed.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More