.NET Arrays
Arrays are one of the most fundamental data structures in programming. In .NET, arrays provide a way to store a collection of items of the same data type under a single variable name. Understanding arrays is essential for efficient programming as they allow you to manage multiple related values more effectively than using individual variables.
What is an Array?
An array is a data structure that contains a fixed number of elements of a single type. Think of an array as a row of boxes, each holding a value, with each box numbered starting from zero.
Key characteristics of arrays in .NET:
- Fixed size (cannot be resized after creation)
- Zero-based indexing (first element is at index 0)
- Store elements of the same data type
- Stored in contiguous memory locations
Declaring and Initializing Arrays
Basic Array Declaration
In C#, you can declare an array using square brackets []
after the data type:
// Declare an array of integers with size 5
int[] numbers = new int[5];
In this example, we've created an array that can hold 5 integers. Each element is initialized with the default value for that type (0 for integers).
Array Initialization with Values
You can initialize an array with values at the time of declaration:
// Initialize array with values
int[] scores = new int[] { 85, 92, 78, 95, 88 };
// Shorthand syntax
string[] fruits = { "Apple", "Banana", "Orange", "Mango", "Grape" };
Multidimensional Arrays
.NET supports multidimensional arrays. The most common are 2D arrays:
// 2D array (3 rows, 4 columns)
int[,] matrix = new int[3, 4];
// Initialize a 2D array with values
int[,] grid = new int[,] {
{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 }
};
Jagged Arrays (Arrays of Arrays)
Jagged arrays are arrays of arrays, where each sub-array can have a different length:
// Declare a jagged array
int[][] jaggedArray = new int[3][];
// Initialize the sub-arrays
jaggedArray[0] = new int[] { 1, 2, 3 };
jaggedArray[1] = new int[] { 4, 5, 6, 7 };
jaggedArray[2] = new int[] { 8, 9 };
Accessing Array Elements
Array elements are accessed using zero-based indexing:
int[] numbers = { 10, 20, 30, 40, 50 };
// Access the first element
Console.WriteLine(numbers[0]); // Output: 10
// Access the third element
Console.WriteLine(numbers[2]); // Output: 30
// Modify an element
numbers[1] = 25;
Console.WriteLine(numbers[1]); // Output: 25
For multidimensional arrays:
int[,] matrix = new int[,] {
{ 1, 2, 3 },
{ 4, 5, 6 }
};
// Access element at row 1, column 0
Console.WriteLine(matrix[1, 0]); // Output: 4
For jagged arrays:
int[][] jaggedArray = new int[][] {
new int[] { 1, 2 },
new int[] { 3, 4, 5 }
};
// Access element at row 1, column 2
Console.WriteLine(jaggedArray[1][2]); // Output: 5
Array Properties and Methods
Array Length
The Length
property returns the total number of elements in the array:
int[] numbers = { 10, 20, 30, 40, 50 };
Console.WriteLine(numbers.Length); // Output: 5
int[,] matrix = new int[3, 4];
Console.WriteLine(matrix.Length); // Output: 12 (3×4)
For multidimensional arrays, you can use GetLength(dimension)
to get the length of a specific dimension:
int[,] matrix = new int[3, 4];
Console.WriteLine(matrix.GetLength(0)); // Output: 3 (rows)
Console.WriteLine(matrix.GetLength(1)); // Output: 4 (columns)
Common Array Methods
.NET provides many useful methods for working with arrays:
Array.Sort()
int[] numbers = { 5, 2, 8, 1, 9 };
Array.Sort(numbers);
// numbers is now { 1, 2, 5, 8, 9 }
foreach (int num in numbers)
{
Console.Write(num + " "); // Output: 1 2 5 8 9
}
Array.Reverse()
int[] numbers = { 1, 2, 3, 4, 5 };
Array.Reverse(numbers);
// numbers is now { 5, 4, 3, 2, 1 }
foreach (int num in numbers)
{
Console.Write(num + " "); // Output: 5 4 3 2 1
}
Array.IndexOf()
string[] fruits = { "Apple", "Banana", "Orange", "Mango" };
int position = Array.IndexOf(fruits, "Orange");
Console.WriteLine(position); // Output: 2
Iterating Through Arrays
You can iterate through arrays using various looping constructs:
Using for Loop
int[] numbers = { 10, 20, 30, 40, 50 };
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine($"Element at index {i}: {numbers[i]}");
}
// Output:
// Element at index 0: 10
// Element at index 1: 20
// Element at index 2: 30
// Element at index 3: 40
// Element at index 4: 50
Using foreach Loop
string[] colors = { "Red", "Green", "Blue", "Yellow" };
foreach (string color in colors)
{
Console.WriteLine(color);
}
// Output:
// Red
// Green
// Blue
// Yellow
Practical Examples
Example 1: Calculating Average
public static double CalculateAverage(int[] numbers)
{
int sum = 0;
foreach (int number in numbers)
{
sum += number;
}
return (double)sum / numbers.Length;
}
// Usage
int[] scores = { 85, 92, 78, 95, 88 };
double average = CalculateAverage(scores);
Console.WriteLine($"Average score: {average}"); // Output: Average score: 87.6
Example 2: Finding Maximum Value
public static int FindMaximum(int[] numbers)
{
int max = numbers[0];
for (int i = 1; i < numbers.Length; i++)
{
if (numbers[i] > max)
{
max = numbers[i];
}
}
return max;
}
// Usage
int[] temperatures = { 23, 29, 25, 32, 27, 22 };
int maxTemp = FindMaximum(temperatures);
Console.WriteLine($"Maximum temperature: {maxTemp}°C"); // Output: Maximum temperature: 32°C
Example 3: Frequency Counter
public static Dictionary<string, int> CountFrequencies(string[] items)
{
Dictionary<string, int> frequencies = new Dictionary<string, int>();
foreach (string item in items)
{
if (frequencies.ContainsKey(item))
{
frequencies[item]++;
}
else
{
frequencies[item] = 1;
}
}
return frequencies;
}
// Usage
string[] fruits = { "Apple", "Banana", "Apple", "Orange", "Banana", "Apple" };
Dictionary<string, int> fruitCounts = CountFrequencies(fruits);
foreach (var fruit in fruitCounts)
{
Console.WriteLine($"{fruit.Key}: {fruit.Value}");
}
// Output:
// Apple: 3
// Banana: 2
// Orange: 1
Common Array Challenges
Array Bounds
One common error when working with arrays is accessing elements outside the array's bounds:
int[] numbers = { 1, 2, 3 };
// The following line will throw an IndexOutOfRangeException
// Console.WriteLine(numbers[3]); // There is no element at index 3!
Always check that your index is within the valid range: 0
to array.Length - 1
.
Passing Arrays to Methods
Arrays are reference types, so when you pass an array to a method, the method can modify the original array:
public static void DoubleValues(int[] numbers)
{
for (int i = 0; i < numbers.Length; i++)
{
numbers[i] *= 2;
}
}
// Usage
int[] values = { 1, 2, 3 };
DoubleValues(values);
// values is now { 2, 4, 6 }
Summary
Arrays in .NET are powerful and versatile data structures that allow you to:
- Store multiple values of the same type under a single variable
- Efficiently access elements using indices
- Perform operations on collections of data
- Store data in multiple dimensions
Understanding arrays is crucial for solving many programming problems and is the foundation for understanding more complex data structures like lists, dictionaries, and queues.
Exercises
- Create an array of 10 integers, fill it with random numbers between 1 and 100, and then calculate the sum and average.
- Write a method that reverses an array without using the built-in
Array.Reverse()
method. - Create a 3x3 matrix using a 2D array, fill it with numbers, and calculate the sum of the main diagonal.
- Write a method that merges two sorted arrays into a single sorted array.
- Create a program that counts how many times each letter appears in a string using an array of 26 elements (one for each letter of the alphabet).
Additional Resources
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)