One of the most used (important) data structures in C# is arrays. It helps developers to store and manage collection of elements efficiently. For most programming languages working with arrays is crucial, whether it’s about handling lists of numbers, strings, or even more complex objects. This guide offers the entire range of arrays, from basic declarations to advanced ones.
In this article, I’m going to take you through the ins and outs of arrays in C#, from static / dynamic arrays, initialization techniques, accessing elements, modifying elements, and more complicated stuff like multidimensional / jagged arrays. In addition, we’ll also explore how to take full advantage of the vast and rich toolkit provided by System.Linq namespace for operations on arrays and how to use its array methods such as Sort(), and array properties such as Length.
Declaring an Array
Declaring Static Arrays
C# Static Array is an array with a fixed size, which basically means the number of elements a static array holds cannot change once the array was declared. If you know how many elements your array will have, static arrays are perfect.
In order to declare a static array or any other array for that matter, simply declare the data type of an element in the static array as well as the name of the static array by following up with square brackets [], just like this. The size of the array can be specified after square brackets are put into it.
int[] numbers = new int[5];
In the example above, let’s say we have an integer array called numbers which can simply hold five integers. The memory for the new is allocated with the new keyword. Now at this point each array elements is initialized to default value of integers, i.e, zero.
Declaring Dynamic Arrays
C#’s dynamic arrays are arrays or collections that can resize themselves on the fly as needed, so you can add or remove elements run time. But the built in C# array structure is static and you can use collections like List<T> from the System.Collections.Generic namespaces to create dynamic behavior.
A List<T> is a generic collection with built in dynamic resizing — it’s a flexible alternative to static arrays. If you declare a List<T> the type of elements inside square brackets.
List<int> dynamicNumbers = new List<int>();
Here you can see that dynamicNumbers is a list of any number of integers. You can have methods that try to add elements to this list with methods like Add() and remove elements from this list with Remove(), RemoveAt(). The List<T> type has a dynamic nature and is quite versatile in cases when we don’t know up front how many items we need to place in the list.
Initializing an Array
Initializing Static Arrays
Often when you declare a static array, you’ll also want to initialize it with values. You can init an array at the time of declaration by a comma separated list of values enclosed in curly braces {}
int[] evenNumbers = new int[5] { 2, 4, 6, 8, 10 };
For example, in the above example the evenNumbers array is created with five integer values. The number of elements matches the size [5]. You can also omit the size, and the compiler will think it out for you depending on how many elements you have.
string[] weekdays = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" };
In this case we don’t have to have ‘say the size’ explicitly when we are using the weekdays array, it is initialized with 5 string elements.
Initializing Dynamic Arrays
List<T> is a dynamic array, it can be initialized similarly, but with minor differences. You start List<T> empty, so you add elements using the Add() method.
List<string> fruits = new List<string>();
fruits.Add("Apple");
fruits.Add("Banana");
fruits.Add("Cherry");
You can also initialize a List with a collection of elements with an object initializer, alternatively.
List<string> vegetables = new List<string> { "Carrot", "Lettuce", "Spinach" };
This method is a way to initialize a dynamic array with initial values.
Implicitly Typed Arrays
Implicitly typed array expressions are available in C# with the var keyword and with implicitly typed arrays. It works as a feature, which allows compiler to infer the type of array based upon which assigned values are.
var primeNumbers = new[] { 2, 3, 5, 7, 11 };
As shown above, primeNumbers is inferred such that it’s an array of integers. Implicit typing cuts down on republicity, and makes code more readable, but does so to the detriment of code clarity, therefore it should be used with caution.
var mixedTypes = new object[] { 1, "two", 3.0 };
That’s where we have mixedTypes, it’s an array of objects, with mix types.
Getting and Setting Array Values
Accessing Array Values
Indexing starts at zero and we use indices to access elements in an array. To access an element’s index, you use square brackets [].
int[] numbers = { 10, 20, 30, 40, 50 };
int firstNumber = numbers[0]; // 10
int thirdNumber = numbers[2]; // 30
As an example above, firstNumber stores the first element of numbers and thirdNumber stores the third element.
IndexOutOfRangeException will be thrown if we try to access an index out of range of the array.
Iterate over an Array
By doing iteration on array you can take action on each of the elements. For this purpose, generally for loop and foreach loop are used.
string[] colors = { "Red", "Green", "Blue" };
// Using a for loop
for (int i = 0; i < colors.Length; i++)
{
Console.WriteLine(colors[i]);
}
// Using a foreach loop
foreach (string color in colors)
{
Console.WriteLine(color);
}
The for loop (or some implementations) will provide you access to the index of each element, depending on your needs. If you are only reading the elements themselves, the foreach loop saves you from having to write a for loop, which is a little simpler.
Changing Array Values
You just can assign new value for some of the items in an array.
char[] vowels = { 'a', 'e', 'i', 'o', 'u' };
vowels[2] = 'x'; // Changing 'i' to 'x'
When you run the above code, vowels now has { ‘a’, ‘e’, ‘x’, ‘o’, ‘u’ } in it. To avoid any exceptions we want to check if the index you’re modifying is within the array bounds.
double[] temperatures = new double[3];
temperatures[0] = 98.6;
temperatures[1] = 99.1;
temperatures[2] = 97.8;
We were able to assign values to each element of the temperatures array, one at a time.
Multidimensional Arrays
2-D Arrays
Multidimensional arrays are also an array, which means, you can store data in a grid like structure. In fact, a 2-D array is simply an array of arrays — this is to represent matrices or tables.
To create a 2 dimensional array we use the square brackets and we use commas to say how many dimensions are needed to create the array.
int[,] matrix = new int[3, 3];
This code, creates 3×3 integer matrix. You can assign values at the time of declaration.
int[,] grid = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Accessing elements in a 2-D array requires two indices: There are one for row and one for column.
int centerValue = grid[1, 1]; // 5
3-D Arrays
A 3 D array takes the concept of multidimensional arrays to 3 dimensions and is very useful in representing some data in cube like structure.
int[,,] cube = new int[2, 2, 2];
This code declares that a 2x2x2 integer array. It gets more complicate when initializing a 3 D array because of an extra dimension.
int[,,] tensor = {
{
{1, 2},
{3, 4}
},
{
{5, 6},
{7, 8}
}
};
Three indices are used to access elements in a 3-D array.
int value = tensor[1, 0, 1]; // 6
However, multidimensional arrays can be used, but add complexity to your code, so you need to think if they are the best structure to hold your data.
Jagged Arrays
Jagged arrays are arrays of arrays, but the “inner” arrays can be of different lengths. They are different from multidimensional arrays, where the elements of each dimension may have a fixed sized.
int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[] {1, 2};
jaggedArray[1] = new int[] {3, 4, 5};
jaggedArray[2] = new int[] {6};
Again in our example here, jaggedArray contains three arrays of integers of varying sizes.
Getting/Setting Values
Accessing elements in a jagged array requires two sets of indices: We need one for the outer array, and another for the inner array.
int firstElement = jaggedArray[0][0]; // 1
int secondElement = jaggedArray[1][1]; // 4
You can also change the values of specific indices in a jagged array, and you can assign new value to modify elements.
jaggedArray[2][0] = 9; // Changing 6 to 9
After completing this assignment, the third inner array of the last element of jagged array is now 9.
Array Operations using System.Linq
Powerful Querying and manipulation methods for arrays are contained within the System.Linq Namespace. Although LINQ (Language Integrated Query) doesn’t provide any new capabilities on its own, it does let you write expressive code for filtering, ordering, and projecting your data.
using System.Linq;
One example is that LINQ can be used to find all even numbers in an array.
int[] numbers = { 1, 2, 3, 4, 5, 6 };
var evenNumbers = numbers.Where(n => n % 2 == 0).ToArray();
In this case, evenNumbers will be an array that will contains {2, 4, 6}.
LINQ can also be used to sort an array.
string[] names = { "Charlie", "Alice", "Bob" };
var sortedNames = names.OrderBy(n => n).ToArray();
sortedNames
that will contain { "Alice", "Bob", "Charlie" }
.
LINQ doesn’t just provide Select(), First(), Count(), but more, and offers sophisticated operations with very little code.
What is Length in Arrays?
The Length property of course returns the total number of items in the array.
int[] scores = { 88, 74, 92, 100, 67 };
int totalScores = scores.Length; // 5
When iterating over arrays, it is important to understand Length in order to prevent an IndexOutOfRangeException.
for (int i = 0; i < scores.Length; i++)
{
Console.WriteLine(scores[i]);
}
The scores array in this loop will be printed out.
Conclusion
In C#, arrays are such a basic part of programming that it allows us to store and modify collections of data in an efficient way. Being able to handle arrays properly is vital for every C# developer: from basic declarations to just the powerful thing like multidimensional and jagged arrays.
We have talked about how to declare and init variables of both static array and dynamic array, how to access and modify the element of array and how to do operations on System.Linq. Knowing how to use Sort() and what Length is will help you to work even better with arrays.
In this guide, with the aid of these concepts and techniques, you’ll be prepared to deal with the majority of the present programming challenges that involve arrays in C#.