Best Tutorials C# Intermediate

C# Arrays

This article aims to familiarize you with the C#Arrays. Arrays can be One-Dimensional or Multi-Dimensional, but the most commonly used ones are Single-Dimensional ArraysRectangular Arrays, and Jagged Arrays. You will learn how to declare, create, initialize and use these arrays—finally, different ways to access the values of these arrays.

Table of Contents
Watch Now C# Arrays tutorial has related videos created by the Codebuns. Watch it with the written material for a STEP-BY-STEP explanation with CODE examples. Videos will reduce your learning curve and deepen your understanding where you’re uncertain: C# Single Dimensional Array | C# Rectangular Array | C# Jagged Array

What Is an Array?

Array is a data structure that stores multiple values of the same type in a single variable. You access each individual value through an integer index with an array name. Arrays can be of different dimensions like Single-dimension, Multi-dimension or Jagged array. The simplest of all is Single dimension, so you’ll start learning how to declare, initialize, and use single dimensional array.

What Is Single-Dimensional Array?

The below image shows a C# single-dimensional array of eight integers, which contains array elements from 0 to 7. Array’s smallest and largest indexes are called its lower and upper bound, respectively. The lower bound is always 0, and the upper bound is always one less than the length of the array (arrayLength – 1). That means if an array has eight elements, their indices are 0, 1, 2, 3, 4, 5, 6, and 7.

C# Single Dimensional Array

Arrays also have GetLowerBound and GetUpperBound methods that return the lower and upper bounds for a particular dimension in an array.

Note: if you use an index that’s greater than the upper bound, an IndexOutOfRangeException will be thrown.

 
Edit, and test all the CODE examples used in this article with C# online editor:  Single-Dimensional Array Code Playground

Declare and Initialize One-Dimensional Array in C#

You can create an array using either one or two statements.

Using Two Statements

An array is declared by defining the type of elements inside the array, followed by empty square brackets [ ] and a variable name.

Syntax

type[] arrayName; // declaration: initial value is null

Example

int[] integerValues;
C# Single Dimensional Array Declaration

However, the above statement only declares the variable. It does not yet initialize an array. You do the initialization part with the new keyword, followed by the data type and a second set of square brackets containing the length or size of the array.

Syntax

arrayName = new type[arrayLength]; // initialization: Creates an array object.

Example

integerValues = new int[4];
C# Single Dimensional Array Initialization

Using One Statement

Declaration and initialization of an array at the same time on a single line.

Syntax

type[] arrayName = new type[arrayLength]; // declaration & initialization

Example

int[] integerValues = new int[4];
C# Single Dimensional Array Declaration Initialization

Create and Assign Values to One-Dimensional Array

You can reference array elements using an index inside square brackets, one at a time, and then assign values, as shown below. The index of the first element always starts with 0.

int[] integerValues = new int[4];
integerValues[0] = 1;
integerValues[1] = 2;
integerValues[2] = 3;
integerValues[3] = 4;
C# Single Dimensional Array Initialization With Value

You can use another method, which is quite convenient. With this method, values can be assigned simultaneously using CURLY BRACKET {…} NOTATION. This syntax is valid when creating an array of a known size and wants to specify the initial values quickly.

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

You can also use the var keyword with an array to declare a variable that infers its type from its assigned value. Use new keyword when using this approach.

var integerValues = new[] { 1, 2, 3, 4 };

Update One-Dimensional Array Value

You can access a value of an indexed array element by using indexer [ ] and then assign a value to it.

integerValues[1] = 20;

Above statement assigns a value 20 to the 2nd column with an index [1], which updates the value from 2 to 20.

integerValues[3] = 40;

The above statement assigns a value of 40 to the 4th column with an index [3], which updates the value from 4 to 40.

C# Single Dimensional Array Set Individual Element

Access One-Dimensional Array Values

You can retrieve a specific value in the array using an index position inside the square brackets [ ]. Use 0, 1, 2, and 3 indexes to access array elements.

Syntax

arrayName[index];

Example

Console.WriteLine(integerValues[1]); // return 2

Above statement gets the value 2 from the 2nd column with an index [1].

Console.WriteLine(integerValues[3]); // return 4

Above statement gets the value 4 from the 4th column with an index [3].

C# Single Dimensional Array Get Individual Element

There are two kinds of multi-dimensional arrays: Rectangular and Jagged.

What Is Rectangular Array in C#?

C# rectangular array is an array of two (or more) dimensions separated by a COMMA. You can think of a rectangular array as a table, where the first dimension is the number of rows, and the second dimension is the number of columns keeping in mind that every row is the same length. Due to 2 dimensions, it’s also known as a two-dimensional or 2D array.

C# Rectangular Array
 
Edit, and test all the CODE examples used in this article with C# online editor:  Rectangular Array Code Playground

Declare and Initialize Rectangular Array in C#

You can create an array using either one or two statements.

Using Two Statements

On the left side of the declaration, you need to have a data type, the type of values in the array like it will hold integer values, decimal, string etc. Followed by COMMA (,) within the set of BRACKETS ([ ]). The comma indicates that the array has two dimensions. Two or more commas would indicate three or more dimensions.

Syntax

type[,] arrayName;

Example

int[,] intArray;
C# Rectangular Array Declaration

new keyword is used to create an array on the right side of instantiation. You specify the number of ROWS in the array, followed by a COMMA, and then the number of COLUMNS to set the size of each dimension in the array.

Syntax

arrayName = new type[rows, columns]; // 2D array
  • type[,] indicates 2D array
  • type[rows, columns] indicates size of ROW and COLUMN.

Example

intArray = new int[3, 2];
C# Rectangular 3x2 Array (2.1)
C# Rectangular Array Initialization

Note: Multi-dimensional array is indexed by two or more integers.

Using One Statement

Declaration and initialization of an array at the same time on a single line.

Syntax

type[,] arrayName = new type[rows, columns];

Example

int[,] intArray = new int[3, 2];
C# Rectangular Array Declaration Initialization (3)

Create and Assign Values to a Rectangular Array

Array elements can be referenced using two integers with an indexer, one statement at a time to assign values to the elements of the intArray as shown below.

int[,] intArray = new int[3, 2];

intArray[0, 0] = 1;
intArray[0, 1] = 2;
intArray[1, 0] = 3;
intArray[1, 1] = 4;
intArray[2, 0] = 5;
intArray[2, 1] = 6;

There’s a shorter form below.

int[,] intArray = { { 1, 2 }, { 3, 4 }, { 5, 6 } };

Run Demo

Access Individual Rectangular Array Values

You refer array element using its ROW and COLUMN index because each element of multi-dimensional array is identified with an index for each dimension.

Syntax

arrayName[rowIndex, columnIndex]

You access each array element using two integers with an indexer.

Example

Console.WriteLine(intArray[1, 1]); // 0
C# Rectangular Array Get Value By Index (4)

Run Demo

Accessing Rectangular Array Values Using Nested for Loops

Never hardcode the total number of elements when iterating through the array. Always use properties or methods such as Length and GetLength to determine the total number of iterations needed. Let’s look at the following examples.

3 by 2 Array Example

string display = string.Empty;

int[,] intArray = { 
  { 1, 2 }, 
  { 3, 4 }, 
  { 5, 6 } 
};

for (int row = 0; row < intArray.GetLength(0); row++)
{
    for (int column = 0; column < intArray.GetLength(1); column++)
    {
        //Console.WriteLine(intArray[row, column]);
        // OR
        display += intArray[row, column] + " ";
    }

    display += "\n";
}

Console.WriteLine(display);

Run Demo

OUTPUT

1 2
3 4
5 6

First, declared and initialized rectangular intArray variable. On the left side of the declaration, a single COMMA (,) within square brackets indicate that the array is two-dimensional, where the dimensions are 3 × 2 (3 ROWS and 2 COLUMNS). The array is two-dimensional, so you need to use 2 separate for loops to iterate through each dimension. Outer for loop is to get the number of ROWS by calling the GetLength method and passing 0 for the 1st dimension and nested for loop, which brings the number of COLUMNS for each row by passing 1 for the length of the 2nd dimension.

The line Console.WriteLine(intArray[row, column]); prints each element to the console. When retrieving the individual value from an array element, you use variable intArray with the loop counter row for rowIndex and column for columnIndex within square brackets [ ].


What Is a Jagged Array in C#?

C# jagged array is an array of arrays, which means it’s an array that contains other arrays (inner arrays for clarity). Of course, such inner arrays can have different lengths, or they can even be not initialized. Think of a table with the rows of unequal lengths.

When you create a jagged array, you declare the number of fixed rows. Then, each row can have a different number of columns. Specifically, jagged is a single-dimensional array, where each row will hold another array of different dimensions 😊.

If you look at the following example, you will see a jagged array with three rows/elements. ROW 0 has two columns, ROW 1 has four columns, while the last ROW 2 has three columns:

C# Jagged Array

Note: The elements of the jagged array can be one-dimensional and multi-dimensional arrays.

Edit, and test all the CODE examples used in this article with C# online editor:  Jagged Array Code Playground

Declare and Initialize a Jagged Array in C#

You can create an array using either one or two statements.

Using Two Statements

To declare a jagged array, we use two sets of square brackets in the array’s declaration. The notation ([ ][ ]) is used after the data type to represent the number of dimensions. Here is an example of a jagged array declaration:

Syntax

type[ ][ ] arrayName;

Syntax to Declare Jagged Array (Array of Arrays)

Only the size determining the number of ROWS in the first pair of brackets is used to initialize the jagged array. Also, notice that the second bracket that defines the number of elements inside the row is EMPTY because every row has a different number of columns. The column sizes must be set individually.

Syntax

arrayName = new type[rows][ ];

Syntax to Initialize Jagged Array (Array of Arrays)

Using One Statement

Another way is to declare and initialize an array at the same time on a single line.

Syntax

type[ ][ ] arrayName = new type[rows][ ];

Syntax to Declare and Initialize Jagged Array (Array of Arrays)

Create a Jagged Array

The below line creates fruits with two elements, each of type string[] and with an initial value of null.

string[][] fruits = new string[2][]; // correct
Declare Jagged Array of string with 2 Rows

string[2][ ] indicates a jagged array has 2 rows, and the number of columns is unclear.

When you use the new keyword to create the jagged array, you specify the number of rows that the array will contain.

The following statement is a syntax error:

string[][] fruits = new string[2][2]; // error

A jagged array cannot be created entirely with a single statement. Instead, you need to initialize the elements of a jagged array separately.

Assign Values to a Jagged Array

Once the array is declared, you need to construct each row and fill it with data. There are two ways to allocate the elements—one per row or using an initialization list to assign data simultaneously.

Using the first method, you can write:

fruits[0] = new string[2];
fruits[1] = new string[3];

The above lines initialize the two elements of fruits with individual array instances of different dimensions—one statement at a time.

Declare And Initialize Jagged Array of string With 2 Rows
  • fruits[0] = new string[2] indicates row 0 has 2 columns.
  • fruits[1] = new string[3] indicates row 1 has 3 columns.

Let’s take a closer look at the index values for the above array.

Index Values of a Jagged Array of string With 2 Rows

You can access an indexed array element, which is part of the jagged array using two indexers ([rowIndex] [columnIndex]), and then assign a value to it with the assignment operator (=). Look at the following statements.

fruits[0][0] = "Apple";
fruits[0][1] = "Apricot";

fruits[1][0] = "Mango";
fruits[1][1] = "Orange";
fruits[1][2] = "Melon";
Assign values to the Indexes of a Jagged Array of string With 2 Rows
  • fruits[0][0] = “Apple” indicates value Apple assigned to the 1st column [0] of the 1st row [0]
    fruits[0][1] = “Apricot” indicates value Apricot assigned to the 2nd column [1] of the 1st row [0]
  • fruits[1][0] = “Mango” indicates value Mango assigned to the 1st column [0] of the 2nd row [1]
    fruits[1][1] = “Orange” indicates value Orange assigned to the 2nd column [1] of the 2nd row [1]
    fruits[1][2] = “Melon” indicates value Melon assigned to the 3rd column [2] of the 2nd row [1]

Another way that allows initial values of the array elements to be assigned is with the new operator using an array initializer, a list of values written between the curly bracket { and }.

fruits[0] = new string[] { "Apple", "Apricot" };
fruits[1] = new string[] { "Mango", "Orange", "Melon" };

The above code adds three separate one-dimensional arrays—one statement at a time.

  • The first element [0],which is an string array with two columns. The columns are initialized with the values Apple and Apricot.
  • The second element [1],which is an string array with three columns. The columns are initialized with the values Mango, Orange and Melon.

In the second method, you can use a modified form of the above and assign values all at once using an array initializer.

string[][] fruits = { new string[] { "Apple", "Apricot" }, new string[] { "Mango", "Orange", "Melon" } }; 

Note: The length of the array is inferred from the number of values between the delimiters {}.

Another approach is to use the var keyword. This keyword instructs the compiler to implicitly type a local variable:

var fruits =  new[] { new string[] { "Apple", "Apricot" }, new string[] { "Mango", "Orange", "Melon" } }; 

Run Demo

Access Individual Values of a Jagged Array

You refer to each element of the array using its ROW and COLUMN index with two indexers ([ ][ ]).

Syntax

arrayName[rowIndex][columnIndex]

Example

fruits[1][1];

Let me repeat this.

You enclose the ROW and COLUMN index in their brackets to access an item stored at a particular row and column in a jagged array. For example, the above fruits[1][1] statement displays the value stored at ROW 1COLUMN 1, of the fruits, as shown here:

Access Individual Elements of a Jagged Array

Access whole row of data using the following syntax.

Syntax

arrayName[row]

Example

fruits[1]
Access Whole Row Data of Jagged Array

Let’s display values using foreach loop.

string display = string.Empty;  

foreach (string rowValue in fruits[1]) 
{        
    display +=   rowValue + " ";

    // line break
    display += "\n"; 
}  
Console.WriteLine(display);

Run Demo

OUTPUT

Mango
Orange
Melon


Jagged Array vs Multidimensional Array

Both jagged and rectangular arrays are a form of multidimensional arrays, but the simplest one is a two-dimensional array.

A jagged array is like a two-dimensional array, but the “ROWS” in a jagged array can have a different number of columns. If you use ([ ][ ]), you are creating an array of arrays, where each array within a larger array has a different length.

Note: Inner arrays within the main array need not be equal size.

A traditional two-dimensional array has a rectangular size, where each “ROW” has the same number of columns. For this reason, a 2D array is often called a square array or a rectangular array where each array within a larger array has the same length.

Note: Inner arrays within the main array are equal size.

Jagged Array vs Multidimensional Array

The jagged array shown contains three rows, the first row containing two elements, the second row with four elements, and the third row with three elements.

The following code shows an example of how the jagged array is created and initialized.

// Create an array of 3 int arrays.
 int[][] intArray = new int[3][]; 

// Create each array that is an element of the jagged  
intArray[0] = new int[] { 1, 2 };
intArray[1] = new int[] { 3, 4, 5, 6 };
intArray[2] = new int[] { 7, 8, 9 }; 

Let’s look at the following image.

Jagged Array Example

Rectangular arrays are created using commas to separate each dimension. The following code declares a two-dimensional array, where the dimensions are 3 × 2:

int[,] intArray = new int[3, 2];

Assign values to the elements of the intArray using one statement at a time, as shown below.

intArray[0, 0] = 1;
intArray[0, 1] = 2;
intArray[1, 0] = 3;
intArray[1, 1] = 4;
intArray[2, 0] = 5;
intArray[2, 1] = 6;
two-dimensional array example

Run Demo


C# Reference | Microsoft Docs