Arrays
An array is a row of same-type boxes with a fixed size, each with a number starting at zero. Like an egg carton, you cannot add more slots once it is made.
In this page:
Syntax
type[] arrayName = new type[length];
type[] arrayName = { value1, value2, value3 };
arrayName[0]; // first element
arrayName.Length;
Arrays
An array is a fixed-size, ordered collection of elements of the same type, indexed starting at 0. Once created, its length cannot change. Arrays are the most basic collection type and back many of the more flexible collections internally.
Warning:
Accessing an index outside the array's bounds throws an
IndexOutOfRangeException at runtime.Example: Arrays
using System;
class Program
{
static void Main(string[] args)
{
int[] numbers = { 10, 20, 30, 40 };
Console.WriteLine(numbers.Length);
Console.WriteLine(numbers[0]);
numbers[1] = 99;
foreach (int n in numbers)
{
Console.WriteLine(n);
}
}
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Reading or writing
arr[arr.Length], when the last valid index isLength - 1, which throwsIndexOutOfRangeException. - Trying to add an element to an array, when its size is fixed once created; use
List<T>for that. - Assigning one array to another and expecting a copy, when both variables refer to the same array.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: