C# Arrays
In this chapter you will learn:
- What is Array
- How to create Array
- Array for loop
- Bounds Checking
- Example to create an array and set value for each element
- Create for loop to iterate C# array
Description
An array represents a fixed number of elements of a particular type.
All arrays inherit from the System.Array class, providing common services for all arrays.
Syntax
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.
An array is denoted with square brackets after the element type. For example:
char[] vowels = new char[5]; // Declare an array of 5 characters
Square brackets also index the array, accessing a particular element by position:
vowels [0] = 'a';
vowels [1] = 'e';
vowels [2] = 'i';
vowels [3] = 'o';
vowels [4] = 'u';
Console.WriteLine (vowels [1]); // e
/* w ww . ja v a2s . c om*/
This prints "e" because array indexes start at 0. We can use a for loop statement to iterate through each element in the array.
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;/* www . j a v a2 s . c om*/
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.
Array for loop
The for loop in this example cycles the integer i from 0 to 4:
for (int i = 0; i < vowels.Length; i++) {
Console.Write (vowels [i]); // aeiou
}
Bounds Checking
All array indexing is bounds-checked by the runtime. If you use an invalid index, an IndexOutOfRangeException is thrown:
int[] arr = new int[3];
arr[3] = 1;// IndexOutOfRangeException thrown
Example
The following code sets the elements in an array with index and then output them:
using System;//from w w w. jav a 2 s .co m
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:
Example 2
We can use for loop the iterate each element in an array.
using System;/* ww w.j a va 2s. c o m*/
class Program
{
static void Main(string[] args)
{
int[] intArray = new int[10];
for (int i = 0; i < intArray.Length; i++)
{
intArray[i] = i;
}
for (int i = 0; i < intArray.Length; i++)
{
Console.WriteLine(intArray[i]);
}
}
}
The output:
Next chapter...
What you will learn in the next chapter:
- What is C# Array Length
- How to access C# Array Length
- How to use array length property
- How to get array length with GetLength function
- GetLength() and two dimension array