C# ยท Chapter 21 of 46

C# Arrays

An array stores multiple values of the same type in a single variable, accessed by an index starting at 0. Arrays have a fixed size once created.

Arrays are useful when you need to work with a collection of related values, like a list of scores or names, and want fast, index-based access to each item.

Syntax
type[] name = {value1, value2};
name[index];

Declaring and accessing arrays

Arrays are declared with square brackets, like `int[] numbers = {1, 2, 3};`. Elements are accessed using their zero-based index, so numbers[0] is the first element.

Array properties and iteration

The Length property gives the number of elements. You can loop through an array using a for loop with the index, or a foreach loop for simpler iteration.

Example 1 (csharp)
using System;

class Program {
  static void Main() {
    int[] numbers = { 10, 20, 30 };
    Console.WriteLine(numbers[0]);
    Console.WriteLine(numbers.Length);
  }
}
Output
10
3

numbers[0] accesses the first element, and Length gives the total count.

Example 2 (csharp)
using System;

class Program {
  static void Main() {
    string[] fruits = { "apple", "banana", "cherry" };
    for (int i = 0; i < fruits.Length; i++) {
      Console.WriteLine(fruits[i]);
    }
  }
}
Output
apple
banana
cherry

The loop visits each index from 0 to Length-1, printing each fruit.

Key points

  • Arrays store multiple values of the same type.
  • Array indexes start at 0.
  • Arrays have a fixed size once created.
  • The Length property gives the total number of elements.
๐Ÿ’ก Note: Accessing an index outside the array's bounds throws an IndexOutOfRangeException.

๐Ÿ“ Quick Quiz

1. What index does the first element of an array have?

2. Which property gives the number of elements in an array?

3. Can an array's size change after it is created?