How to use Array in C#
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 .
string[] week = new string[7];
week[0] = "Sunday";
week[1] = "Monday";
The above C# code declare a string array of 7 strings and assign some values to it.
string[] week = new string[] {"Sunday","Monday","Tuesday"};
The above code declare and initialize a string array with values.
string str = week[1];
We can access the Arrays elements by providing its numerical index, the above statement we access the second value from the week Array.
In the following program , we declare an Array "week" capable of seven String values and assigns the seven values as days in a week . Next step is to retrieve the elements of the Array using a for loop. For finding the end of an Array we used the Length function of Array Object.
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";
for (int i = 0; i < = week.Length-1; i++)
{
MessageBox.Show(week[i]);
}
}
}
}
|
|