Reading Array Elements
In this lesson, we will look at how array elements are indexed, how to get them by index, and what happens when you access a non-existent element.
Indexing array elements
An index is the position number of an element in an array.
Indexing starts at zero.
Let's continue using the movie theater row analogy. Suppose a row has 4 seats total, and the first 3 are occupied; then the array might look like this:
- Seat 1 (index 0) - Ivan
- Seat 2 (index 1) - Kate
- Seat 3 (index 2) - Pete
- Seat 4 (index 3) - empty
Or in C#:
Line 1, Char 1
Reading elements
Knowing the index, you can easily get an array element.
Line 1, Char 1
Going out of bounds
If you try to access an element that does not exist, the program will throw an
IndexOutOfRangeException Line 1, Char 1
or
Line 1, Char 1
How to check an index before reading
An array has a
Length property that indicates the number of elements in the array. To avoid an exception when reading, it is common to check that the index is within the bounds of the array Line 1, Char 1
Summary
In this lesson you learned:
- how to read array elements by index
- that indexing in C# starts at zero
- what IndexOutOfRangeException is
- how to avoid errors and check the index
Exercises
- Print the first and last elements of the array.
Line 1, Char 1
- Try to print elements with index 4 and index -1. What will happen? Why?
Line 1, Char 1
- Write a method PrintFruit that takes an index and prints the array element if the index is valid; otherwise prints the message "Invalid index!"
Line 1, Char 1