Array in C sharp is basically continues memory allocation of given type and size. We create array by using [].
Array Declaration
int[] data = new int[5];
In the given syntax we just created an array of size 5 and type is int.
When we create an array the object of Array class has been initialized in the memory and allocates the space according to size and type. We access the each element of array using index which starts from zero.
int[] data = new int[5];
data[0] = 100;
data[1] = 105;
data[2] = 209;
data[3] = 300;
data[4] = 789;
As we know that when we declare an array then object of Array class has been created in the memory, so we have many properties, methods to work with array.
There is Length property in Array class which give the size of array.
We can use this Length property to traverse the array in following manner:-
int[] data = new int[5];
data[0] = 100;
data[1] = 105;
data[2] = 209;
data[3] = 300;
data[4] = 789;
Response.Write("Traversal Using For Loop <br/>");
for (int i = 0; i < data.Length; i++)
{
Response.Write(data[i] + "<br/>");
}
Response.Write("Traversal Using Foreach Loop <br/>");
foreach (int res in data)
{
Response.Write(res + "<br/>");
}
The output of this code will be as follows:-
Figure 1
We have the following ways to initialize the values in array:-
int[] data = { 3, 4, 5, 6, 9 };
int[] data = new int[] { 3, 4, 5, 6, 9 };
int[] data = new int[5] { 3, 4, 5, 6, 9 };
For any query you can send mail at info@techaltum.com Thanks