CSharp.Net-Informations.com
   Home      .Net Framework      VB.NET      C#                                                                      About


  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 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.

  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 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.

         C# Source Code Download           Print Source Code
         How to use C# foreach loop - Download
        
C# Tutorial

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);
            }
        }
    }
}



CSharp Statements Related Contents
*     How to use C# if else statements
*     How to use C# for loop
*     How to use C# while loop
*     How to use C# do while loop
*     How to use C# switch case statements
*     How to use C# exceptions statements


   Home      VB.NET      C#
CSharp Related Topics
*     An overview of Microsoft CSharp
*     C# Language Tutorial
*     C# Statements Tutorial
*     C# Collection Tutorial
*     C# String Tutorial
*     C# File Operations Tutorial
*     C# Excel Tutorial
*     C# Crystal Reports Tutorial
*     CSharp Communication Tutorial
*     C# Ado.Net Tutorial and Source Code
*     C# ADO.NET data Providers Tutorial
*     C# Dataset Tutorial
*     C# DataAdapater Tutorial
*     Csharp DataView Tutorial
*     Csharp Remoting Tutorial
*     C# XML Tutorial
*     C# DataGridView Tutorial
   Home      VB.NET      C#
More Source Code :   
Mail to :  feedback@net-informations.com
  |  Home   |  VB.NET   |  C#   |  SiteMap   |  Terms of Use   |  About   |
net-informations.com (C) 2010
All Rights Reserved. All other trademarks are property of their respective owners.