← Back to C# Course | Chapter 9: Collections | Lesson 1 of 7

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:

  1. Arrays
Syntax
csharp
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

markup
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);
        }
    }
}
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
  1. Reading or writing arr[arr.Length], when the last valid index is Length - 1, which throws IndexOutOfRangeException.
  2. Trying to add an element to an array, when its size is fixed once created; use List<T> for that.
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.