CSharp examples for Language Basics:Array
An array represents a fixed number of variables (elements) of a particular 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:
using System;/*from ww w . jav a 2s .co m*/ class Test { static void Main(){ char[] vowels = new char[5]; // Declare an array of 5 characters vowels[0] = 'a'; vowels[1] = 'e'; vowels[2] = 'i'; vowels[3] = 'o'; vowels[4] = 'u'; Console.WriteLine (vowels[1]); // e } }
The for loop in this example cycles the integer i from 0 to 4:
using System;/*from w w w .ja va 2 s . c o m*/ class Test { static void Main(){ char[] vowels = new char[5]; // Declare an array of 5 characters vowels[0] = 'a'; vowels[1] = 'e'; vowels[2] = 'i'; vowels[3] = 'o'; vowels[4] = 'u'; for (int i = 0; i < vowels.Length; i++) Console.Write (vowels[i]); // aeiou } }
The Length property of an array returns the number of elements in the array.
Once an array has been created, its length cannot be changed.
An array initialization expression lets you declare and populate an array in a single step:
char[] vowels = new char[] {'a','e','i','o','u'};
or simply:
char[] vowels = {'a','e','i','o','u'};
All arrays inherit from the System.Array class, providing common services for all arrays.