Common Array Operations
Explore how to perform common array operations in C# including reading elements, inserting at specific positions, updating values, and deleting elements. Understand how fixed-size arrays differ from dynamic List<T> collections and learn how operation costs vary based on location in the array.
Before writing any algorithm, we need to know what we can actually do with an array. Arrays support a small, fixed set of operations. In C#, a built-in array has a fixed length, while List<T> is commonly used when we need a dynamic array-like collection. These operations cover reading values, adding new ones, changing them, removing old ones, and scanning through the collection.
In this lesson, we will go through each operation one by one.
Access (Read an element)
The most basic thing you can do with an array is read a value stored in it. This is called accessing an element. Think of it like looking up a specific game on our scorecard.
Syntax:
To access an element, we write the array name followed by the index of the element we want to access in square brackets:
array[index]
Example: Consider the following scores array: [88, 95, 70, 82, 91]. If we want to access the score of game 3, we use scores[2], which gives us 70.
C# implementation:
The following code shows how to access the score at index 2 from the scores array:
Note: Trying to access an index that does not exist, for example, scores[10] in a five-element array, will throw an error such as IndexOutOfRangeException for arrays or ArgumentOutOfRangeException for List<T>.
Insertion (Add an element)
Insertion means adding a new element. In C#, a regular array has a fixed length, so for insertion examples we will use List<T>, which behaves like a dynamic array. The cost of insertion depends on where the new element goes.