C# Tutorial · Control Flow · Lesson 10 of 22
C# Arrays
Single and multi-dimensional arrays, indexes, ranges and Array methods.
Arrays
Arrays have a fixed length. Indexes start at 0; ^1 means "last", and ranges like [1..3] slice:
int[] nums = { 42, 7, 19, 3 };
string[] names = new string[3]; // filled with null
names[0] = "Ada";
Console.WriteLine($"{nums.Length} {nums[0]} {nums[^1]}");
Console.WriteLine(string.Join(",", nums[1..3]));
Array.Sort(nums);
Console.WriteLine(string.Join(",", nums));
Console.WriteLine(Array.IndexOf(nums, 19) + " " + nums.Contains(7));
int[,] grid = { { 1, 2, 3 }, { 4, 5, 6 } };
Console.WriteLine($"{grid[1, 2]} rows={grid.GetLength(0)} cols={grid.GetLength(1)}");
Output
4 42 3 7,19 3,7,19,42 2 True 6 rows=2 cols=3
Run this on your computer — see “Get Started” for setup.
Need a list that grows? Use List<T>.
Test yourself
What does arr[^1] return?
The first elementThe last elementAn errorThe length
Show answer
Answer: The last element
Practice next
- Two Sum · coding problem
- Binary Search · coding problem