Arrays are a fundamental data structure in C#, allowing you to store multiple values of the same type in a single variable. They provide a way to efficiently manage and access collections of data. In this blog, we’ll explore different ways to declare, initialize, and use arrays in C#.
Declaring and Initializing Arrays
1. Basic Array Declaration
You can declare an array in C# by specifying the type and size:
int[] numbers = new int[5]; // Creates an array of size 5 with default values (0)
This initializes an array with five elements, all set to the default value of 0.
2. Array with Predefined Values
You can also initialize an array with predefined values:
int[] numbers = { 1, 2, 3, 4, 5 };
Or explicitly using new:
int[] numbers = new int[] { 1, 2, 3, 4, 5 };
Multidimensional Arrays
C# supports multidimensional arrays, such as 2D arrays:
int[,] matrix = new int[2, 3] { { 1, 2, 3 }, { 4, 5, 6 } };
This creates a 2×3 matrix.
Jagged Arrays
A jagged array is an array of arrays, where each sub-array can have a different length:
int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[] { 1, 2 };
jaggedArray[1] = new int[] { 3, 4, 5 };
jaggedArray[2] = new int[] { 6 };
Can We Have an Array Without a Fixed Size?
Unlike lists, arrays in C# require a fixed size at the time of declaration. You must specify the size when using new:
int[] numbers = new int[5]; // Valid
If you need a dynamically sized collection, use List<T>:
List<int> numbers = new List<int>();
numbers.Add(1);
numbers.Add(2);
numbers.Add(3);
Console.WriteLine(numbers.Count); // Output: 3
Accessing and Modifying Array Elements
You can access and modify elements using an index:
int[] numbers = { 10, 20, 30, 40, 50 };
numbers[1] = 25; // Modifies the second element
Console.WriteLine(numbers[1]); // Output: 25
Iterating Over Arrays
Using a for loop:
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine(numbers[i]);
}
Using foreach:
foreach (int num in numbers)
{
Console.WriteLine(num);
}
Conclusion
Arrays are a powerful tool in C#, offering efficient storage and access for collections of data. However, they require a fixed size, so for dynamic data structures, List<T> might be a better choice. Understanding arrays will help you build efficient and performant C# applications.
Happy coding! 🚀