2D Arrays in C#: How To Use Them

Dec 15, 2023 | C#, .NET

Welcome! Let’s begin by acknowledging the infinite wisdom of arrays in C#. Aren’t they mind-blowingly amazing? In this article, we are going to delve into one of the more advanced array structures known as 2D arrays in C#. Buckle up!

Introduction to 2D Arrays in C#

“Oh! a 2D Array? Isn’t that mathematics?!” You might ask. Well, not exactly, although we do borrow the terminology from mathematics. In the cosmos of programming, a 2D array is just a fancy way to store and organize our data in rows and columns. Now, wouldn’t that be super handy?!

What are 2D Arrays in C#?

2D Arrays in C#, sometimes called a “matrix”, is essentially an array of arrays. It’s like a double whammy of storing spaces, where each data snippet is identified by two indices rather than one.

int[,] matrix = new int[3,3]; // a 3x3 2D array

The above matrix is a playground, 3 blocks wide and 3 blocks high. And you, my friend, are the orchestrator deciding what goes where in this C# double array playground.

Understanding Panels: C# Two Dimensional Array

Don’t be frightened by the lingo “Panel” here. It’s simply another moniker for a good ol’ 2D array in C#. It allows you to play around with data in two dimensions. Imagine each value in the array as an inhabitant of a building, where every policyholder has a floor number and room number. That’s pretty neat, right?

Working with 2D Arrays in C#

Feel the thrill yet? Yes, we’re slowly unwrapping the C# dynamic array cube. Next up, we’ll examine how to set this package up and then play around with it.

Declaration and Initialization of C# 2D Array

Declaring a C# Two Dimensional Array is straightforward. It’s as simple as deciding the number of rows and columns you need!

int[,] my2DArray = new int[4,2];  // a 4x2 2D array

The above line of malicious code creates a 2D array with 4 rows and 2 columns, ready to be packed with data. Seem simple enough?

Accessing Elements in a 2D Array in C#

Whether you’re looking to access or modify elements in your C# double array, you need to know their exact location. It’s sort of like retrieving a file from a well-organized filing cabinet.

my2DArray[0, 0] = 12; // adds 12 in the first row and first column
int firstValue = my2DArray[0, 0]; // fetches the first value

How to Create a 2D Array in C#

Now that we’ve learned all the basics, let’s jump into creating our very first 2D array in C#. Trust me, it’s going to be as engaging as crafting a Lego brick masterpiece.

Static Allocation of 2D Arrays in C#

In C#, static allocation means setting up the space needed at compile time. Imagine planning how many rooms your Lego building will have before actually starting construction.

string[,] matrix = new string[5,3]; // a 5x3 2D array

Dynamic Allocation of 2D Arrays: C# Dynamic Array

Unlike static allocation, dynamic allocation is more like playing Lego without following the manual. You decide the size of the array at runtime, like adding rooms to your Lego building on a whim.

int[][] dynamicArray = new int[n][]; // where 'n' is a variable
for (int i = 0; i < n; i++)
{
    dynamicArray[i] = new int[m]; // where 'm' is a variable
}

Navigating C# 2D Array

Feeling the adrenaline rush yet? Now, let’s navigate through the maze of our 2D array and get familiar with all the nooks and corners.

Using Loops to Navigate C# 2D Array

Navigating through C# Two Dimensional Array is sort of like moving through a sudoku grid. You start from the top left corner and traverse through each row before moving on to the next.

for (int i = 0; i < matrix.GetLength(0); i++)
{
    for (int j = 0; j < matrix.GetLength(1); j++)
    {
        // access matrix[i, j] here
    }
}

With the loop’s help, you gracefully dance through every cell in the array. Easy-peasy, right?

Using Multidimensional Array Methods in C#

Now, remember how the 2D array was an array of arrays? Well, .GetLength(0) gets the length of the first dimension, and .GetLength(1) gets the length of the second. It’s like having a map to guide you through the maze of arrays!

Manipulating 2D Arrays

Manipulating data is a vital operation when it comes to handling arrays in any programming language. In C#, 2D arrays are no different. Let’s explore how we can apply various methods to twist and turn our 2D arrays as per our demand.

Methods of Manipulating C# Double Array

In our C# double array, we have different ways to manipulate the data or the structure of the array itself. Operations like resizing the array dimensions, sorting the array elements, and copying the array data onto another array are some of the common methods programmers use to achieve their desired outcomes.

Resizing

Let’s start with resizing. Imagine that we initially created a 2D array with 2 rows and 2 columns. But later, we realized that we need to add another row to accommodate more data. How can we achieve this in C#?

int[,] initialArray = new int[2, 2] 
{ 
    { 1, 2 }, 
    { 3, 4 } 
};

// We need to convert to a jagged array for resizing
int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[] { 1, 2 };
jaggedArray[1] = new int[] { 3, 4 };
jaggedArray[2] = new int[] { 5, 6 };

With the help of jagged arrays in C#, we can add a new row to our existing array, enabling us to resize dynamically.

Sorting

Sorting a 2D array can also be quite straightforward in C#. Suppose we have a 2D array of integers, and we want to sort the numbers in ascending order. To achieve this, we first convert the multidimensional array into a single dimension, apply the sort operation, and then convert it back. Here’s an example:

int[,] numbers = 
{
    {5, 12, 17, 9, 3},
    {13, 4, 8, 15, 6},
    {9, 11,3, 2, 15},
    {0, 10, 14, 7, 5}
};

    var len = numbers.Length;
    var flat = new int[len];
    Buffer.BlockCopy(numbers, 0, flat, 0, len * sizeof(int));
    Array.Sort(flat);

    var sorted = new int[numbers.GetLength(0), numbers.GetLength(1)];
    Buffer.BlockCopy(flat, 0, sorted, 0, len * sizeof(int));

With the above code, our 2D array numbers is sorted in ascending order.

Copying and Resizing with C# Dynamic Array

So, let’s say we’ve created our 2D array, filled it with data, and now we want to copy this data to another array without disturbing the original array. How do we do that? No worries, C# has you covered!

int[,] arrayA = new int[2,2] 
{ 
    { 1, 2 },
    { 3, 4 } 
};

// create arrayB with the same dimensions as arrayA and copy all arrayA content 
int[,] arrayB = (int[,])arrayA.Clone();

Just like photocopying a document, the Clone() method in C# can be used to replicate the entire 2D array content into another array.

Further resizing operations and manipulations can be done by converting the 2-Dimensional array into a so-called “jagged array”, where each row can have a different number of columns. These resizing operations can be useful for example, in scenarios where spaces are dynamically allocated based on user input or real-time data.

Conclusion: Understanding and Using 2D Arrays in C#

So, we’ve made it to the end. Ah, the sigh of accomplishment! Working with C# 2D arrays is like manoeuvring through a mind-boggling labyrinth. But guess what? You’ve mastered it! So go ahead, brag about your newfound coding prowess! You’re now a 2D array wizard in C#. Now, wasn’t that an interesting journey?

Remember: The power of 2D arrays in C# lies not in code, but in its application. So go forth, and may your code conquer all odds!

You May Also Like

Sign up For Our Newsletter

Weekly .NET Capsules: Short reads for busy devs.

  • NLatest .NET tips and tricks
  • NQuick 5-minute reads
  • NPractical code snippets
.