DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Generics in Java and Their Implementation
  • The Two-Pointers Technique
  • Arrays and Hashing
  • Mule 4 DataWeave(1.x) Script To Resolve Wildcard Dynamically

Trending

  • Contract-First Integration: Building Scalable Systems With Flyway, OpenAPI, and Kafka
  • Building a High-Throughput Distributed Sequence Generator Using the Hi-Lo Algorithm
  • MuleSoft IDP: Enhancing Efficiency and Accuracy in Data Extraction
  • When Snowflake Lies to You: Understanding False Failures in dbt Pipelines
  1. DZone
  2. Data Engineering
  3. Data
  4. Master C# Arrays: The Basics

Master C# Arrays: The Basics

Master C# Arrays fast with this step-by-step article and videos containing demo code and images. C# rectangular and jagged arrays are also covered.

By 
Pirzada .Rashid user avatar
Pirzada .Rashid
·
Mar. 21, 23 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
3.6K Views

Join the DZone community and get the full member experience.

Join For Free

C# Arrays tutorial has related videos. Watch this C# arrays tutorial with both related videos and 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.

What Is an Array?

An 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 the single dimension, so you’ll start learning how to declare, initialize, and use a single-dimensional array.

What Is a 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 lower and upper bounds. 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 an array's lower and upper bounds for a particular dimension.

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

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

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


Example

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

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


Example

C#
 
integerValues = new int[4];

C# Single Dimensional Array Initialization

Using One Statement

Declaration and initialization of an array simultaneously on a single line.

Syntax

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


Example

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

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


C# Single Dimensional Array Initialization With ValueCURLY BRACKET {…} NOTATION.

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 indexer [ ] and then assign a value to it.

C#
 
integerValues[1] = 20;


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

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 [ ]. Access array elements using 0, 1, 2, and 3 indexes.

Syntax

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

C# Single Dimensional Array Get Individual Element


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

What Is a 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


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

C#
 
type[,] arrayName;


Example

C#
 
int[,] intArray;

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

C#
 
arrayName = new type[rows, columns]; // 2D array


  • type[,] indicates 2D array
  • type[rows, columns] indicates the size of ROW and COLUMN.

Example

C#
 
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 simultaneously on a single line.

Syntax

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


Example

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

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

Access Individual Rectangular Array Values

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

Syntax

C#
 
arrayName[rowIndex, columnIndex]


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

Example

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

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

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 where each row holds 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.

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

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

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

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


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

Create a Jagged Array

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

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

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

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";

  • 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] is a string array with two columns. The columns are initialized with the values Apple and Apricot.
  • The second element [1] is a 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.

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

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

C#
 
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 whole row of data using the following syntax.

Syntax

C#
 
arrayName[row]


Example

C#
 
fruits[1]


Let’s display values using foreach loop.

C#
 
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 or rectangular array where each array within a larger array has the same length.

Note: Inner arrays within the primary array are equal in size.

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.

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;


Run Demo

Data structure Strings Data Types Array data type

Published at DZone with permission of Pirzada .Rashid. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Generics in Java and Their Implementation
  • The Two-Pointers Technique
  • Arrays and Hashing
  • Mule 4 DataWeave(1.x) Script To Resolve Wildcard Dynamically

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook