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 for each loop in C# Array



Arrays are using for store similar data types grouping as a single unit. We can access Array elements by its numeric index. The array indexes start at zero. The default value of numeric array elements are set to zero, and reference elements are set to null. Click the following link to learn more about C# Arrays.

C# ArrayArray Declaration and initialization

string[] week = new string[] {"Sunday","Monday","Tuesday"};

Retrieve a single item from Array.

string str = week[1];

It is very convenient to retrieve the Array elements using foreach loop. The following C# program shows how to retrieve the elements in an Array using foreach loop.

using System;
using System.Collections;
using System.Windows.Forms;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string[] week = new string[7];
            week[0] = "Sunday";
            week[1] = "Monday";
            week[2] = "Tuesday";
            week[3] = "Wednsday";
            week[4] = "Thursday";
            week[5] = "friday";
            week[6] = "Saturday";

            foreach (string day in week)
            {
                MessageBox.Show(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