C# Simplified, part 3 - Arrays
(Page 4 of 6 )
Arrays are not new to C#. They exist in all programming languages such as C, C++ and Java. They enable you to store a list of items of similar data type. For example, to store the age of students you can use an array of type integer. Similarly, if you have to store their names, addresses, and so forth, you can use a string data type.
In C#, arrays are derived from the Array class found in the System namespace. This class contains lot of properties and methods, which you can manipulate for your various programming tasks.
Arrays in C# are declared in the same manner as in Java and C++, and they can be either single or multi-dimensional. Listing 3.5 declares a single dimensional array of type integer and with a dimension of 10. Dimension indicates the number of array elements which you can store in the variable named x.
Listing 3.5
int[] x = new int[10]
Arrays can also be declared as in the code given in listing 3.6:
Listing 3.6
int[] x = {2,3,4,5,6}
The above code snippet stores five integer values. In C#, the index position for the first element is zero. In listing 3.7, an array variable is declared with four values and they are printed using the for loop.
Listing 3.7
using System;
class ArraysDemo
{
public static void Main()
{
int[] x = {10,20,30,40,50};
for(int i = 0; i<=4;i++)
{
Console.WriteLine(x[i]);
}
}
}
Instead of supplying the condition inside the for loop, you can apply the Length property of the Array class to determine the dimensions of an array, as shown in listing 3.8:
Listing 3.8
using System;
class ArraysDemo2
{
public static void Main()
{
int[] x = {10,20,30,40,50};
for(int i = 0; i<x.Length;i++)
{
Console.WriteLine(x[i]);
}
}
}
C# also supports so called multi-dimensional arrays, as shown in the code snippets given below:
// Three dimensional array (Count number of commas and add 1 to it)
int[,,] x
// Two dimensional array
int[,] y
Next: Using Array.Rank >>
More C# Articles
More By Anand Narayanaswamy