Array
In this chapter you will learn:
What is an Array
An array is a collection of variables of the same type that are referred to by a common name. The length of an array is fixed. Array type is declared by putting square brackets after the data type. To declare a one-dimensional array, you will use this general form:
type[ ] array-name = new type[size];
System.Array
is a base class for all arrays in C#.
Array elements can be of any type, including an array type.
System.Array
implements IEnumerable and IEnumerable<T>
,
you can use foreach iteration on all arrays in C#.
Arrays are zero indexed: an array with n elements is indexed from 0 to n-1.
using System;/*from j a v a2 s . co m*/
class MainClass
{
static void Main()
{
int[] arr = new int[] { 15, 20, 5, 25, 10 };
Console.WriteLine("GetType() = {0}", arr.GetType());
}
}
The code above generates the following result.
The default value of numeric array elements are set to zero, and reference elements are set to null. An array can be Single-Dimensional, Multidimensional or Jagged.
A jagged array is an array of arrays, and therefore its elements are reference types and are initialized to null.
The following code declare an array type for int
.
int[] intArray;
The size of an array is declared when allocating memory for its elements.
We use the new
operator to allocate memory for array.
int[] intArray = new int[100];
To reference an element from an array, we put the index inside the square bracket.
intArray[2]
The index of an array starts at 0, so the code
above is referencing the third element in intArray
.
The following code sets the elements in an array with index and then output them:
using System;// ja v a 2 s. c om
class Program
{
static void Main(string[] args)
{
int[] intArray = new int[10];
intArray[0] = 3;
intArray[1] = 4;
intArray[2] = 5;
Console.WriteLine(intArray[0]);
Console.WriteLine(intArray[1]);
Console.WriteLine(intArray[2]);
}
}
The output:
Next chapter...
What you will learn in the next chapter: