C# Programming Tutorial 0/45 lessons ~6 min read Lesson 21

    Arrays

    Arrays are fixed-length, zero-indexed contiguous collections — T[].

    Course progress0%
    Focus
    10 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    Arrays are fixed-length, zero-indexed contiguous collections — T[]. They underpin buffers, interop, and performance-critical code. List is more common in business logic, but arrays appear in APIs, params arguments, and Span scenarios.

    Multi-dimensional and jagged arrays confuse interviewees. Modern code prefers ReadOnlySpan and Memory for slicing without allocation. This lesson covers declaration, initialization, bounds, and LINQ integration.

    The story

    A cold-chain logistics company attaches temperature sensors to refrigerated trucks. Each trip produces a fixed batch of hourly readings stored in an array. Before alerting dispatch, software computes the average temperature and normalizes readings by subtracting the mean — operations that benefit from Span<T> to avoid copying large buffers.

    Understanding the topic

    Key concepts

    • Fixed size set at creation — cannot grow.
    • Zero-based indexing; Length property.
    • Rank: single, multidimensional int[,], jagged int[][].
    • Covariant string[] assigned to object[] — reference arrays only.
    • Index/range: arr[^1], arr[1..3] slice.
    • Arrays implement IList but fixed size Add throws.

    Step-by-step explanation

    1. int[] nums = new int[5]; default initialized to 0.
    2. Initializer: int[] { 1, 2, 3 } or [1, 2, 3] collection expression.
    3. foreach iterates elements; for uses index.
    4. Array.Copy, Clone for duplication.
    5. LINQ: arr.Where(...).ToArray() materializes new array.
    6. Buffer.BlockCopy for primitive byte blitting.

    Practical code example

    Daily temperature buffer with collection expression (C# 12) and span-friendly processing:

    csharp
    namespace TechLearningPro.Arrays;
    public static class TemperatureAnalyzer
    {
    public static double AverageCelsius(ReadOnlySpan<double> readings)
    {
    if (readings.IsEmpty) throw new ArgumentException("No readings.");
    double sum = 0;
    foreach (var t in readings)
    sum += t;
    return sum / readings.Length;
    }
    public static double[] Normalize(double[] input)
    {
    var avg = AverageCelsius(input);
    return [.. input.Select(v => v - avg)]; // collection expression spread
    }
    }

    Line-by-line code explanation

    • AverageCelsius(ReadOnlySpan<double> readings) accepts a span view over array memory without copying.
    • if (readings.IsEmpty) throw ... rejects empty input before dividing by zero.
    • double sum = 0 initializes an accumulator for the average calculation.
    • foreach (var t in readings) iterates each temperature reading in the span.
    • sum += t adds each value to the running total.
    • return sum / readings.Length computes the arithmetic mean.
    • Normalize(double[] input) accepts a classic array for the normalization step.
    • var avg = AverageCelsius(input) reuses the span-based average over the array.
    • return [.. input.Select(v => v - avg)] uses a collection expression spread to build a new normalized array.

    Key takeaway: ReadOnlySpan accepts arrays without copy. Collection expression [.. spread] creates new array from LINQ.

    Real-world use

    Where you'll use this in production

    • Image pixel buffers and signal processing.
    • Interop with native APIs expecting pointers.
    • Batch job chunking fixed-size partitions.
    • Algorithm interview problems on arrays.

    Best practices

    • Use List when size unknown or mutable.
    • Use Span/ReadOnlySpan for performance slices.
    • Check bounds or use Try pattern for index access.
    • Prefer IEnumerable return unless array specifically needed.
    • Document fixed-size assumptions in public APIs.

    Common mistakes

    • IndexOutOfRangeException from off-by-one.
    • Assuming jagged and rectangular arrays same syntax.
    • Using + for array concatenation — use Concat.ToArray.
    • Modifying foreach collection — N/A for arrays but relevant for array-backed lists.

    Advanced interview questions

    Q1BeginnerArray vs List?
    Array fixed size; List dynamic with Add/Remove.
    Q2BeginnerDefault value of int array elements?
    0 — value types zeroed; references null.
    Q3IntermediateJagged vs multidimensional?
    Jagged int[][] ragged rows; int[,] rectangular grid.
    Q4IntermediateWhy Span over array slicing?
    Span views memory without allocating subarray.
    Q5AdvancedRotate array k steps in-place O(n) time O(1) space.
    Reverse whole array, reverse first k, reverse remainder — classic interview algorithm.

    Summary

    Arrays are fixed-length indexed collections. Spans provide allocation-free slicing over arrays. Collection expressions simplify array/list initialization in C# 12. Prefer List for mutable unknown-size collections. Next: List dynamic collections.

    Ready to mark this lesson complete?Track your journey across the entire course.