1. Introduction
What do you usually want to do with arrays?
Let's list the basic operations:
- Read and change array elements by index.
- Search for an element by value.
- Copy an array, create "slices" (part of an array).
- Sort an array.
- Reverse an array.
- Fill an array with a value.
- Check if an element exists (does the array contain a given value).
- Resize (change the length).
In real-world tasks, you run into these actions all the time — like, "is there a sum above 4000?", "find the first price below 1000", "sort prices in ascending order", and so on.
And for all of this, we've got functions
| Operation | Method / Syntax | Features |
|---|---|---|
| Change by index | |
Error if out of bounds |
| Search by value | |
-1 if not found |
| Check existence | |
Lambda or function |
| Sort | |
Array changes in place |
| Reverse | |
Changes element order |
| Copy | |
Shallow copy |
| Fill | |
Fills with one value |
| Resize | |
New elements — default |
| Find max/min | |
Needs Linq |
2. Reading and Changing Elements by Index
We already know this, but let's lock it in with a simple example (let's say we have an array of grades):
// Student's grades array
int[] grades = { 4, 3, 5, 2, 5 };
// Read the first grade
int firstGrade = grades[0];
Console.WriteLine($"First grade: {firstGrade}");
// Change the last grade to "excellent" (5)
grades[^1] = 5;
Console.WriteLine("Changed last grade: " + grades[^1]);
What's important here: zero-based indexing, and if you try to access a non-existent index, you'll get an IndexOutOfRangeException — a classic both in interviews and real life.
3. Searching for an Element in an Array
We've got two functions that search for an element in an array and return its index if found.
Function Array.IndexOf(value [, from])
The Array.IndexOf function searches for the given element from the start of the array. If it finds it, it returns its index. If not — it returns -1.
But what if you want to find the next occurrences of the needed element in the array? For that, you need to pass a second parameter to Array.IndexOf — the index to start searching from. That should be the index of the last found element + 1.
Let's find all occurrences of the number 2 in our array:
int[] grades = { 4, 3, 5, 2, 5, 2 };
int x = 2; // element we're looking for
int index = Array.IndexOf(grades, x);
while (index != -1)
{
Console.WriteLine($"Element {x} found at position: {index}");
// Search for the next index, starting from index + 1
index = Array.IndexOf(grades, x, index + 1);
}
Function Array.LastIndexOf(value [, from])
The Array.LastIndexOf function searches for the given element from the end of the array. If it finds it, it returns its index. If not — it returns -1. Otherwise, it's just like Array.IndexOf.
Let's find all occurrences of the number 2 in our array, but searching from the end:
int[] grades = { 4, 3, 5, 2, 5, 2 };
int x = 2; // element we're looking for
int index = Array.LastIndexOf(grades, x);
while (index != -1)
{
Console.WriteLine($"Element {x} found at position: {index}");
// Search for the next index, starting from previous position - 1
index = Array.LastIndexOf(grades, x, index - 1);
}
4. Checking if an Element Exists in an Array
To check if an element exists, there's the Contains function. This method returns true if the array contains the specified element. For it to work, you gotta add the System.Linq module. Example:
using System.Linq; // Add using System.Linq; if you don't have it
bool hasExcellent = grades.Contains(5);
Console.WriteLine($"Is there a five? {hasExcellent}");
Super simple and clean.
5. Reversing an Array: Array.Reverse
Say you wanna flip an array "backwards". Use this:
int[] grades = { 2, 3, 4, 5 };
// Flip the array
Array.Reverse(grades);
Console.WriteLine("Reversed grades: " + string.Join(", ", grades));
This is super handy for finding the "freshest" data or just if you like looking at the world upside down.
6. Sorting an Array: Array.Sort
Sooner or later you'll want to sort an array. The shortest and safest way — use the standard sort function:
int[] grades = { 4, 3, 5, 2, 5 };
// Sort in ascending order
Array.Sort(grades);
Console.WriteLine("Sorted grades: " + string.Join(", ", grades));
This function also sorts strings, but in alphabetical order.
Sorting in descending order
Standard Array.Sort only sorts ascending. To sort descending, just sort + reverse:
Array.Sort(grades); // First ascending
Array.Reverse(grades); // Then flip it
Console.WriteLine("Descending: " + string.Join(", ", grades));
Note: people often forget that sorting happens "in place": the array changes, you don't get a new one back. If you need the original order, copy the original array first.
7. Cloning an Array: Clone and Array.Copy
If you need to make a copy (and not mess up the original array while processing), use the Clone() and Array.Copy() methods.
The Clone() method should be called on the array, and it'll return a full copy.
The Array.Copy() method needs you to pass in:
- the source array;
- the array to copy data into;
- how many cells to copy.
int[] original = { 1, 2, 3, 4, 5 };
// Way 1: Clone()
// Works for one-dimensional and multi-dimensional arrays, but returns object, so you need a type cast:
int[] copy1 = (int[]) original.Clone();
// Way 2: Array.Copy
int[] copy2 = new int[original.Length];
Array.Copy(original, copy2, original.Length);
Important thing: arrays are copied by value if they're primitive types (int, double). If it's an array of objects, only the references are copied! (so-called "shallow copy").
8. Filling an Array with a Value: Array.Fill
Wanna "zero out" an array or fill it with all fives? There's a handy method for that — Array.Fill:
int[] grades = new int[5];
Array.Fill(grades, 5); // Now all elements are 5
Console.WriteLine("Hypothetically perfect student: " + string.Join(", ", grades));
Useful when you need to quickly initialize an array with a certain value.
9. Finding the Maximum and Minimum Value
The System.Linq module added a bunch of handy methods to arrays, and two of them return the minimum and maximum value in an array. They're called Max() and Min().
Let's find the max or min grade in an array:
int maxGrade = grades.Max();
int minGrade = grades.Min();
Console.WriteLine($"Max grade: {maxGrade}, min: {minGrade}");
Don't forget to add using System.Linq; for these methods.
GO TO FULL VERSION