SkillPilotAI

Arrays, Index and Range

An array stores a fixed number of items of one type, accessed by a zero-based index. Modern C# adds ^ (index from end), .. (range and spread) and collection expressions, which make the classic off-by-one crash easy to avoid.

9.1 Problem: crash on the last order

C#
int[] orders = [499, 1299, 250, 3500]; Console.WriteLine(orders[0]);Console.WriteLine(orders.Length);Console.WriteLine(orders[orders.Length]);
Output
$ dotnet run bug.cs4994Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array.   at Program.<Main>$(String[] args) in ...\bug.cs:line 5
Why orders[orders.Length] crashed
  1. 1.4 items -> valid indexes 0, 1, 2, 3

  2. 2.orders[0] = 499 (first), orders[3] = 3500 (last)

  3. 3.orders.Length = 4, so orders[4] is asked for

  4. 4.C# checks bounds on every access: index 4 does not exist

  5. 5.IndexOutOfRangeException (an off-by-one bug)

Last item = Length - 1 (or ^1)

9.2 Creating arrays

  • new int[3]: three ints, each with the default value 0; the size is fixed.
  • Set values by index: marks[0] = 85.
  • Collection expression: ["Delhi", "Pune", "Jaipur"]; an empty array is [].
C#
int[] marks = new int[3];Console.WriteLine(string.Join(", ", marks)); marks[0] = 85;marks[2] = 92;Console.WriteLine(string.Join(", ", marks)); string[] cities = ["Delhi", "Pune", "Jaipur"];int[] none = [];Console.WriteLine($"{cities.Length} cities");Console.WriteLine($"{none.Length} items");
Output
$ dotnet run create.cs0, 0, 085, 0, 923 cities0 items

9.3 Fix: Index from the end (^)

  • ^1 is the first item from the end (the last); ^2 is the second last.
  • Its type is Index, so you can store it in a variable.
  • orders[orders.Length - 1] gives the same answer, but ^1 is clearer.
C#
int[] orders = [499, 1299, 250, 3500]; Console.WriteLine($"Last: {orders[^1]}");Console.WriteLine($"2nd last: {orders[^2]}"); Index last = ^1;Console.WriteLine(orders[last]);Console.WriteLine(orders[orders.Length - 1]);
Output
$ dotnet run index.csLast: 35002nd last: 25035003500

9.4 Range: more than one item

  • start..end: start is included, end is excluded (1..3 = indexes 1 and 2).
  • ..2: first two items; ^2..: last two items.
  • A range on an array creates a new copy: changing middle does not change orders.
C#
int[] orders = [499, 1299, 250, 3500, 799]; int[] middle = orders[1..3];int[] head = orders[..2];int[] tail = orders[^2..]; Console.WriteLine(string.Join(", ", middle));Console.WriteLine(string.Join(", ", head));Console.WriteLine(string.Join(", ", tail)); middle[0] = 0;Console.WriteLine(orders[1]);
Output
$ dotnet run range.cs1299, 250499, 12993500, 7991299
SyntaxMeaningResult for [499, 1299, 250, 3500, 799]
a[^1]Last item799
a[^2]Second last3500
a[1..3]Index 1 up to (not incl.) 31299, 250
a[..2]First two499, 1299
a[^2..]Last two3500, 799
a[1..^1]Skip first and last1299, 250, 3500

9.5 Collection expression + spread

  • Inside [ ], ..arr spreads that array's items into the new one.
  • The same [ ] syntax works for List<T> too.
C#
int[] morning = [499, 1299];int[] evening = [250, 3500]; int[] today = [..morning, ..evening, 799];Console.WriteLine(string.Join(", ", today)); List<string> cities = ["Delhi", "Pune"];Console.WriteLine(cities.Count);
Output
$ dotnet run spread.cs499, 1299, 250, 3500, 7992

9.6 Multi-dimensional array

  • int[,] is one rectangular block: cinema seats with 3 rows x 4 columns.
  • Access with seats[r, c]; GetLength(0) = rows, GetLength(1) = columns, Length = total (12).
C#
int[,] seats = new int[3, 4];seats[1, 2] = 1;   // bookedint rows = seats.GetLength(0);int cols = seats.GetLength(1);Console.WriteLine($"Seats: {seats.Length}"); for (int r = 0; r < rows; r++){    for (int c = 0; c < cols; c++)        Console.Write($"{seats[r, c]} ");    Console.WriteLine();}
Output
$ dotnet run multi.csSeats: 120 0 0 00 0 1 00 0 0 0

9.7 Jagged array

  • int[][] is an array of arrays: each row is a separate array with its own Length.
  • Good when rows differ in size (different number of orders per day).
  • orders[2][^1]: last order of the third day.
C#
int[][] orders =[    [499, 1299],    [250, 120, 80, 999],    [3500, 799, 120]]; foreach (int[] day in orders){    Console.WriteLine($"{day.Length} orders");}Console.WriteLine(orders[2][^1]);
Output
$ dotnet run jagged.cs2 orders4 orders3 orders120
PointMulti-dimensional int[,]Jagged int[][]
ShapeOne rectangular blockArray of separate arrays
Row lengthsAll the sameCan differ
Accessseats[r, c]orders[r][c]
SizeGetLength(0), GetLength(1)orders.Length, orders[r].Length
ExampleCinema seatsOrders per day

9.8 Common Array helpers

C#
int[] rates = [3500, 499, 1299, 250]; Array.Sort(rates);Console.WriteLine(string.Join(", ", rates)); Console.WriteLine(Array.IndexOf(rates, 1299));Console.WriteLine(Array.IndexOf(rates, 999)); Array.Reverse(rates);Console.WriteLine(string.Join(", ", rates)); int[] stock = new int[4];Array.Fill(stock, 10);Console.WriteLine(string.Join(", ", stock));
Output
$ dotnet run helpers.cs250, 499, 1299, 35002-13500, 1299, 499, 25010, 10, 10, 10
  • Array.Sort and Array.Reverse change the original array in place.
  • Array.IndexOf returns -1 when the value is missing.

9.9 Common mistakes

  • orders[orders.Length]: off by one; the last item is ^1 or Length - 1.
  • orders[-1] like Python: warning CS0251 and a crash at runtime; C# has no negative index.
  • orders[^0] equals Length, so it crashes too.
  • Backup by assignment (int[] backup = prices): same array, so changes show in both. Copy with [..prices].
C#
int[] prices = [499, 1299, 250];int[] backup = [..prices]; prices[0] = 0;Console.WriteLine(backup[0]); // 499 (new copy)

9.10 Interview tips

  • Multi-dimensional = one rectangular block, accessed with [r, c]; jagged = array of arrays with different row lengths.
  • ^ gives an index from the end (^1 = last); .. gives a range with an exclusive end.
  • A range on an array creates a new copy.
  • Arrays are reference types with a fixed size; bounds are checked on every access.