Array length
Learn to get the array length with .Length and understand bounds.
Array length
The .Length property gives the element count of an array. On a three-element array nums.Length returns 3. This is critical for setting loop bounds.
Valid indices run from 0 to nums.Length - 1. Accessing nums[nums.Length] always throws an error; the last valid index is Length - 1. That is why loops use i < nums.Length.
Bounds checking and loops
The safe way to walk an array is the pattern for (int i = 0; i < nums.Length; i++). Here i always stays between 0 and Length - 1; no error is raised.
Using .Length instead of hardcoding bounds makes the code robust; even if the array size changes, the loop adapts. So prefer .Length over constants like for (int i = 0; i < 5; i++).
Exercise Print the array length
Declare a nums array with the value { 7, 8, 9, 10, 11 }. Print nums.Length with Console.WriteLine. The output should be 5.
Show example solution
Write int[] nums = { 7, 8, 9, 10, 11 }; and print it with Console.WriteLine(nums.Length);
Example solution:
using System;
class Program
{
static void Main()
{
int[] nums = { 7, 8, 9, 10, 11 };
Console.WriteLine(nums.Length);
}
}
Test yourself
-
Match each concept to its meaning
- .Length
- Element count
- nums[0]
- First element
- nums.Length - 1
- Last index
- IndexOutOfRange
- Out-of-range error
-
With int[] nums = new int[5]; what is nums.Length?
int[] nums = new int[5]; Console.WriteLine(nums.Length);- 0
- 4
- 6
- 5
Show answer
5 — Correct. new int[5] creates a five-element array; Length is 5.
-
Write the .Length property
int[] nums = {1, 2, 3, 4}; int count = nums____;Show answer
int[] nums = {1, 2, 3, 4}; int count = nums.Length;