Arrays
Arrays are fixed-length, zero-indexed contiguous collections — T[].
Introduction
Arrays are fixed-length, zero-indexed contiguous collections — T[]. They underpin buffers, interop, and performance-critical code. List
Multi-dimensional and jagged arrays confuse interviewees. Modern code prefers ReadOnlySpan
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
- int[] nums = new int[5]; default initialized to 0.
- Initializer: int[] { 1, 2, 3 } or [1, 2, 3] collection expression.
- foreach iterates elements; for uses index.
- Array.Copy, Clone for duplication.
- LINQ: arr.Where(...).ToArray() materializes new array.
- Buffer.BlockCopy for primitive byte blitting.
Practical code example
Daily temperature buffer with collection expression (C# 12) and span-friendly processing:
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 = 0initializes an accumulator for the average calculation.foreach (var t in readings)iterates each temperature reading in the span.sum += tadds each value to the running total.return sum / readings.Lengthcomputes 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
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?
Q2BeginnerDefault value of int array elements?
Q3IntermediateJagged vs multidimensional?
Q4IntermediateWhy Span over array slicing?
Q5AdvancedRotate array k steps in-place O(n) time O(1) space.
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