C# Arrays (With STEP-BY-STEP Videos)
Tags: csharp, intermediat, tutorial, programming
Published: 2023-03-12 15:12:04

![C# Arrays](https://codebuns.com/wp-content/uploads/2023/03/arrays-1024x592.jpg "C# Arrays")

>_C# Arrays tutorial has related videos. 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](https://codebuns.com/csharp-intermediate/single-dimensional-array/) | [C# Rectangular Array](https://codebuns.com/csharp-intermediate/rectangular-array/) | [C# Jagged Array](https://codebuns.com/csharp-intermediate/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](https://codebuns.com/wp-content/uploads/2018/10/single-dimension-array.png "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_.

{% youtube aMA49_rlaXM %}

>_Edit and test all the CODE examples used in this article with C# online editor: [Single-Dimensional Array Code Playground](https://codebuns.com/csharp/csharp-intermediate-code/#single-dimensional-array/)_

### 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
```c#
int[] integerValues;
```
![1-Single-Dimensional-Array-Declaration](https://codebuns.com/wp-content/uploads/2019/05/1-Single-Dimensional-Array-Declaration.png "1-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
```c#
integerValues = new int[4];
```

![2-Single-Dimensional-Array-Initialization](https://codebuns.com/wp-content/uploads/2019/05/2-Single-Dimensional-Array-Initialization.png "2-Single-Dimensional-Array-Initialization")

#### Using One Statement
Declaration and initialization of an array simultaneously on a single line.

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

#### Example
```c#
int[] integerValues = new int[4];
```

![2.1-Single-Dimensional-Array-Declaration-Initialization](https://codebuns.com/wp-content/uploads/2019/05/2.1-Single-Dimensional-Array-Declaration-Initialization.png "2.1-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.

```c#
int[] integerValues = new int[4];
integerValues[0] = 1;
integerValues[1] = 2;
integerValues[2] = 3;
integerValues[3] = 4;
```

![3-Single-Dimensional-Array-Initialization-With-Value](https://codebuns.com/wp-content/uploads/2019/05/3-Single-Dimensional-Array-Initialization-With-Value.png "3-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.

```c#
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.

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

### Update One-Dimensional Array Value
You can access a value of an indexed array element by using an indexer (**[ ]**) and then assign a value to it.

```c#
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**.

```c#
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**.

![6-Single-Dimensional-Array-Set-Individual-Element](https://codebuns.com/wp-content/uploads/2019/05/6-Single-Dimensional-Array-Set-Individual-Element.png "6-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 **[ ]**. Access array elements using 0, 1, 2, and 3 indexes.

#### Syntax
`arrayName[index];`

#### Example
```c#
Console.WriteLine(integerValues[1]); // return 2
```

The above statement gets the value 2 from the 2nd column with an index **[1]**.

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

The above statement gets the value 4 from the 4th column with an index **[3]**.

![5-Single-Dimensional-Array-Get-Individual-Element](https://codebuns.com/wp-content/uploads/2019/05/5-Single-Dimensional-Array-Get-Individual-Element.png "5-Single-Dimensional-Array-Get-Individual-Element")

---

There are two kinds of multi-dimensional arrays: [Rectangular](https://codebuns.com/csharp-intermediate/rectangular-array/) and [Jagged](https://www.codebuns.com/csharp-intermediate/jagged-array/).

## 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.

![1-Rectangular-Array](https://www.codebuns.com/wp-content/uploads/2019/05/1-Rectangular-Array.png "1-Rectangular-Array")

{% youtube ADt-33O9uP4 %}

>_Edit and test all the CODE examples used in this article with C# online editor: [Rectangular Array Code Playground](https://codebuns.com/csharp/csharp-intermediate-code/#rectangular-array)_

### 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 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
```c#
int[,] intArray;
```

![1-Rectangular-Array-Declaration](https://www.codebuns.com/wp-content/uploads/2019/05/1-Rectangular-Array-Declaration.png "1-Rectangular-Array-Declaration")

A **new** keyword creates 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
```c#
intArray = new int[3, 2];
```

![2.1-Rectangular-3x2-array](https://www.codebuns.com/wp-content/uploads/2019/05/2.1-Rectangular-3x2-array.png "2.1-Rectangular-3x2-array")

![2-Rectangular-Array-Initialization](https://www.codebuns.com/wp-content/uploads/2019/05/2-Rectangular-Array-Initialization.png "2-Rectangular-Array-Initialization")

**Note:** _Multi-dimensional array is indexed by two or more integers_.

#### Using One Statement
Declaration and initialization of an array simultaneously on a single line.

#### Syntax
`type[,] arrayName = new type[rows, columns];`

#### Example
```c#
int[,] intArray = new int[3, 2];
```

![3-Rectangular-Array-Declaration-Initialization](https://www.codebuns.com/wp-content/uploads/2019/05/3-Rectangular-Array-Declaration-Initialization.png "3-Rectangular-Array-Declaration-Initialization")

### 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.

```c#
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.
```c#
int[,] intArray = { { 1, 2 }, { 3, 4 }, { 5, 6 } };
```

[Run Demo](https://dotnetfiddle.net/iD04hE)

### 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
```c#
Console.WriteLine(intArray[1, 1]); // 0
```

![4-Rectangular-Array-Get-Value-By-Index](https://www.codebuns.com/wp-content/uploads/2019/05/4-Rectangular-Array-Get-Value-By-Index.png "4-Rectangular-Array-Get-Value-By-Index")

[Run Demo](https://dotnetfiddle.net/70LErJ)

### 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

```c#
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](https://dotnetfiddle.net/m4EyjP)

#### 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 even be not initialized. Think of a table with 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, with each row holding another array of dimensions 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](https://codebuns.com/wp-content/uploads/2020/09/C-Jagged-Array.gif "C-Jagged-Array")

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

{% youtube S1CyNBGZ3eo %}

>_ Edit and test all the CODE examples used in this article with C# online editor: [Jagged Array Code Playground](https://codebuns.com/csharp/csharp-intermediate-code/#jagged-array)_

### 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](https://codebuns.com/wp-content/uploads/2020/09/Syntax-to-Declare-Jagged-Array-Array-of-Arrays.gif "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
```c#
arrayName = new type[rows][ ];
```

![Syntax-to-Initialize-Jagged-Array-Array-of-Arrays](https://codebuns.com/wp-content/uploads/2020/09/Syntax-to-Initialize-Jagged-Array-Array-of-Arrays.gif "Syntax-to-Initialize-Jagged-Array-Array-of-Arrays")

#### Using One Statement
Another way is to declare and initialize an array on a single line simultaneously.

#### Syntax
`type[ ][ ] arrayName = new type[rows][ ];`

![Syntax-to-Declare-and-Initialize-Jagged-Array-Array-of-Arrays](https://codebuns.com/wp-content/uploads/2020/09/Syntax-to-Declare-and-Initialize-Jagged-Array-Array-of-Arrays.gif "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 null value.

```c#
string[][] fruits = new string[2][]; // correct
```

![Declare-Jagged-Array-of-string](https://codebuns.com/wp-content/uploads/2020/09/Declare-Jagged-Array-of-string.gif "Declare-Jagged-Array-of-string")

`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**:

```c#
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:

```c#
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](https://codebuns.com/wp-content/uploads/2020/09/Declare-And-Initialize-Jagged-Array-of-string.gif "Declare-And-Initialize-Jagged-Array-of-string")

- `fruits[0] = new string[2]` indicates row **0** has **2** columns.
- `fruits[1] = new string[3]` indicates row **1** has **3** columns.

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

![Index-Values-of-a-Jagged-Array-of-string](https://codebuns.com/wp-content/uploads/2020/09/Index-Values-of-a-Jagged-Array-of-string.gif "Index-Values-of-a-Jagged-Array-of-string")

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.

```c#
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](https://codebuns.com/wp-content/uploads/2020/09/Assign-values-to-the-Indexes-of-a-Jagged-Array-of-string.gif "Assign-values-to-the-Indexes-of-a-Jagged-Array-of-string")

- `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 **}**.

```c#
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 simultaneously using an array initializer.

```c#
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:

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

[Run Demo](https://dotnetfiddle.net/qgvGhL)

### Access Individual Values of a Jagged Array
You refer to each element of the array using it's **ROW** and **COLUMN** index with two indexers (**[ ][ ]**).

#### Syntax
`arrayName[rowIndex][columnIndex]`

#### Example
```c#
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 1**, **COLUMN 1**, of the **fruits**, as shown here:

![Access-Individual-Elements-of-a-Jagged-Array](https://codebuns.com/wp-content/uploads/2020/09/Access-Individual-Elements-of-a-Jagged-Array.gif "Access-Individual-Elements-of-a-Jagged-Array")

Access the whole row of data using the following syntax.

#### Syntax
`arrayName[row]`

#### Example
```c#
fruits[1]
```

![Access-Whole-Row-Data-of-Jagged-Array](https://codebuns.com/wp-content/uploads/2020/09/Access-Whole-Row-Data-of-Jagged-Array.gif "Access-Whole-Row-Data-of-Jagged-Array")

Let’s display values using the **_foreach_ loop**.

```c#
string display = string.Empty;  
foreach (string rowValue in fruits[1]) 
{        
    display +=   rowValue + " ";
    // line break
    display += "\n"; 
}  
Console.WriteLine(display);
```

[Run Demo](https://dotnetfiddle.net/k7LKAO)

#### 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-vs-Multidimensional-Array](https://codebuns.com/wp-content/uploads/2020/09/Jagged-vs-Multidimensional-Array.gif "Jagged-vs-Multidimensional-Array")

The jagged array shown contains three rows: the **first row** contains two elements, the **second row** has four elements, and the **third row** has three elements.

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

```c#
// 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](https://codebuns.com/wp-content/uploads/2020/09/Jagged-Array-Example.gif "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:

```c#
int[,] intArray = new int[3, 2];
```

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

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

![2d-array-example](https://codebuns.com/wp-content/uploads/2020/09/2d-array-example.gif "2d-array-example")

[Run Demo](https://dotnetfiddle.net/gwqnYg)

## C# Reference | Microsoft Docs

- [Single Dimensional Arrays](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/single-dimensional-arrays)
- [Multidimensional Arrays](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/multidimensional-arrays)
- [C# Jagged Arrays](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/jagged-arrays)
- [Array.Rank Property](https://docs.microsoft.com/en-us/dotnet/api/system.array.rank?view=netcore-3.1)
- [Array.Length Property](https://docs.microsoft.com/en-us/dotnet/api/system.array.length?view=netcore-3.1)