C# Basics

Arrays

An array stores a fixed number of values of the same type, each reached by an index that starts at 0.

How it works

Create, read, change, loop over and sort C# arrays, including 2D arrays.

Length gives the size and ^1 reads the last element. foreach visits every element, Array.Sort sorts in place, new int[3] starts with zeros, and int[,] creates a grid indexed by row and column.

See how it works

Click a box or move the slider to pick an index. Insert or delete to see why every later element has to shift.

Runnable C# example

C#
Run code →
Program.cs
using System;
using System.Linq;

class Program
{
    static void Main()
    {
        // An array has a fixed length set when it is created.
        int[] scores = { 72, 95, 88, 64 };
        Console.WriteLine($"Length: {scores.Length}");
        Console.WriteLine($"First: {scores[0]}, last: {scores[^1]}");

        scores[3] = 70;  // elements can be changed, the length cannot

        int sum = 0;
        foreach (int score in scores)
        {
            sum += score;
        }
        Console.WriteLine($"Sum: {sum}, average: {sum / (double)scores.Length}");

        // Array.Sort sorts in place; string.Join prints the elements.
        Array.Sort(scores);
        Console.WriteLine($"Sorted: {string.Join(", ", scores)}");
        Console.WriteLine($"Max: {scores.Max()}");

        // new int[3] creates an array of zeros.
        int[] counts = new int[3];
        counts[1] = 5;
        Console.WriteLine($"Counts: {string.Join(" ", counts)}");

        // A 2D array is indexed by row and column.
        int[,] grid = { { 1, 2, 3 }, { 4, 5, 6 } };
        Console.WriteLine($"grid[1, 2] = {grid[1, 2]}");
    }
}
Expected output
Length: 4
First: 72, last: 64
Sum: 325, average: 81.25
Sorted: 70, 72, 88, 95
Max: 95
Counts: 0 5 0
grid[1, 2] = 6

Practice with the debugger

Set a breakpoint on an important assignment or condition, click Debug, and inspect the local values before stepping to the next line.

Practice with a challenge

Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.

All challenges