C# Intermediate

C# Single Dimensional Array

The objective of this article is to familiarize you with the C# Single Dimensional Array, also referred as Vectors. Arrays can be of different dimensions, one or two, but the most commonly used one is the One-Dimensional Array or 1D array. You will learn how to declare, create, instantiate and use this type of array. Finally, different ways to iterate through all the elements of the array.

Table of Contents

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.

C# Single Dimensional Array

The above image shows 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 bound and upper bound, respectively. The lower bound is always 0, and the upper bound always one less than the length of the array (arrayLength – 1). That means, if there are eight elements in an array, their indices are 0, 1, 2, 3, 4, 5, 6, 7.

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:  Code Playground

How to Declare One Dimensional Array in C#?

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

Declare and Initialize C# One-Dimensional Array 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. The name of the variable is usually plural because it’s a collection of items.

Syntax

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

Example

int[] integerValues;
C# Single Dimensional Array Declaration

However, 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. This is the fixed number (non-negative integer number) of elements that the array can hold and thus, cannot be changed. Once the array is created, even before you assign any values, the C# compiler automatically assigns each element of the array with a default value for the given data type, which means numeric types are set to zero, char types are set to null, and Boolean types are set to false as indicated by the table here.

Syntax

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

Example

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

An array is a reference type, so memory on the heap (dynamic memory) is allocated to hold the elements using the above initialization statement.

Declare and Initialize C# One-Dimensional Array on a Single Line

Declaration and initialization of an array at the same time on a single line. This declaration also sets aside memory for the array holding n number of types.

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 an Array

An array can store one or more elements. The length, or size, of an array is the number of elements in the array. In other words, the type and length you use for the array must match the number of values assigned to it.

Array elements can be referenced using index inside square brackets, one at a time and then assigned values to it as shown below. 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

In most cases, all of the elements in an array will contain the same type of data, and you’ll declare the array with that data type. However, if you don’t know what type of data an array will contain, you can declare it with the object data type. Then, each element can contain data of any type.

object[] objArray = new object[4];
objArray[0] = 1;
objArray[1] = "Two";
objArray[2] = 3;
objArray[3] = "Four";
C# Single Dimensional Array Initialization With Object Data type

You can use second method, which is quite convenient. With this method, values can be assigned all at once using a curly bracket {…} notation. This syntax is useful when you are creating an array of a known size and want to quickly specify the initial values.

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

If you initialize the array using curly-bracket syntax, then you can omit the size of the array. The C# compiler determines the size from the number of elements assigned to it to create the array, take a look at the following example:

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

You can actually omit the new keyword, data type and a second set of square brackets to make it shorter than the previous syntax.

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 the value that’s assigned to it. You must use the new keyword when using this approach.

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

Assign Value to Array Elements

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;

Above statement assigns a value 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 Array Elements

You can access specific element in the array using an index, which must be an integer type. This index position is used inside the square brackets [ ], known as the array accessor when retrieving the value from an array. In the following example, the elements can be accessed with the index of 0, 1, 2, and 3.

Syntax

arrayName[index];

Example

integerValues[1]; // return 2

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

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

Default Values for Array Elements

When you create an array, each element in the array is initialized to a default value. This value depends on the data type of the array as shown in the following table.

Data Type Default Value
numeric 0
char ‘\0’ (the null character)
Boolean false
DateTime 01/01/0001 00:00:00
Reference types null

Array Property and Methods

C# provides number of useful properties and methods to manipulate array. Some of the most commonly used are listed below.

Property Description
Length Gets the number of elements in all of the dimensions of an array.
Method Description
GetLength(dimension) Gets the number of elements in the specified dimension of an array.
GetUpperBound(dimension) Gets the index of the last element in the specified dimension of an array.
Copy() Copy elements of source array into the destination array.
Sort() Sorts the elements of an array. This array is passed as an argument.
IndexOf() Returns the index position of the first occurrence of a specified value.

Length

Length will return the number of elements in the array.

Syntax

arrayName.Length;

Example

Console.WriteLine(integerValues.Length); // return 4
C# Single Dimensional Array Length

Copy()

This static method allows you to copy the elements of source array into destination array, starting from the first element.

Method Signature: void Copy(Array sourceArray, Array destinationArray, int length);

The first parameter is the source array that provides the values to copy. The second is the destination array that receives the values from the source array. The last parameter is the number of elements to copy.

If you want to copy values of one array into a new array, you use the copy method in the Array class. The following statement allows you to copy first two elements of sourceArray into destArray:

int [] sourceArray = {1, 2, 3, 4, 5, 6};
int [] destArray = {7, 8, 9, 10};

Array.Copy(sourceArray, destArray, 2);

The destArray contains {1, 2, 9, 10} while the sourceArray is unchanged.

Run Demo


Sort()

This method sorts the elements of an array in ascending order. The array is passed as an argument to the Sort method.

Method Signature: void Sort(Array array);

int [] numArray = {3, 1, 2, 4};
Array.Sort(numArray);

The numArray becomes {1, 2, 3, 4}.

Run Demo


IndexOf()

This method searches for a specified value in an array, returning the position of the found value with a numeric index value. The method returns -1 if the value not found.

Let’s look at the following example

int [] numArray = {1, 2, 3, 4};
C# Single Dimensional Array IndexOf Method

To check if the value 3 exists in the array, you write

int result = Array.IndexOf(numArray, 3);
Console.WriteLine(result); // Prints 2

The IndexOf method searches for the value 3 and returns the index of the first value found that is 2 because 3 is the 3rd element in the array. The line System.Console.Write(result); simply prints out the value of result on the Console.

If you write

result = Array.IndexOf(numArray, 5);
Console.WriteLine(result); // Prints -1

The value of result is -1 because 5 does not exist in the numArray.

Run Demo


C# Single Dimensional Array Examples

This statement declares and initializes an array of 3 characters. Once the array is created, you can fill the elements in the array.

char[] grades = new char[3]; // declaration & initialization
C# grades 2d array
grades[0] = 'A';
grades[1] = 'B';
grades[2] = 'C';
C# one dimensional array example
Console.WriteLine(grades.Length); // Yields 3
C# one dimensional array example 1
Console.WriteLine(grades[1]); // Yields B
C# one dimensional array example 2
grades[1] = 'D';

Run Demo

string[] fruits;
fruits = new string[4] { "Apple", "Banana", "Orange", "Papaya" };

string[] Vegetables = new string[5] { "Carrot", "Cucumber", "Tomato", "Onion", "Green Pepper" };

string[] zooAnimals = { "Lion", "Tiger", "Bear" };

var planets = new[] { "Mercury", "Venus", "Earth" };

char[] characters = new char[3] { 'A', 'B', 'C' };
int[] integerValues = new int[3] { 1, 2, 3 };

Decimal[] decimalValues = new decimal[3] { 13.2m, 20.74m, 8.34m };

Note: Console.WriteLine(…); to print the value in console. Replace with the variable name to display the value.

Run Demo


C# Single Dimensional Array IndexOutOfRangeException

string[] movies = new string[3];

movies[0] = "Incredibles 2";
movies[1] = "Avengers: infinity War";
movies[2] = "Black Panther";
movies[3] = "Deadpool 2"; // Exception

Exception

An unhandled exception of type IndexOutOfRangeException occurred: ‘Index was outside the bounds of the array.’

C# movie 2d array

In the example above, an array contains three string elements. It uses indexes 0 through 2 to assign values to those three elements. The length of the array is 3, and the upper bound of the array is 2. If you try to use an index 3, which is greater than the upper bound, the compiler throws an IndexOutOfRangeException exception when the statement is executed, as in the above example.

Run Demo


Processing Array With Loops

Let’s look at the different ways to iterate through single dimensional array elements.

for Loop

The first statement declares an array named arrayValues that contains 3 integer values. You use the Length property to determine how many elements an array contains, which is required to iterate through all the elements of an array. To print each element to the console you use variable with the loop counter i within square brackets [ ] when retrieving the individual value from an array as shown below.

int[] arrayValues = new int[3] { 1, 2, 3 };
for (var i = 0; i < arrayValues.Length; i++)
     Console.WriteLine(arrayValues[i]);

Run Demo

OUTPUT

1
2
3

string[] Vegetables = new string[5] { "Carrot", "Cucumber", "Tomato", "Onion", "Green Pepper" };
for (var i = 0; i < Vegetables.Length; i++)
{
     Console.WriteLine(Vegetables[i]);
}

Run Demo

OUTPUT

Carrot
Cucumber
Tomato
Onion
Green Pepper

Below C# for loop creates an array of 10 integers, all of which are assigned 0 by default. If you want the array to hold values, you must supply them. Here, I have used for loop to fill in the values from 1 to 10. Using for loop you keep track of the current index of the array and access the elements as needed.

int[] intArray = new int[10];
for (int i = 0; i < 10; i++)
     intArray[i] = i + 1; // i will be from 0 to 9

for (int i = 0; i < intArray.Length; i++)
     Console.WriteLine(intArray[i]); // This will print the value from 1 to 10 on the same line

Run Demo

OUTPUT

12345678910

foreach Loop

C# provides, one of the most commonly used constructs for iterating through array elements is the C# foreach loop. Each time the loop runs, an element in the arrayValues is automatically stored in a variable value. The type of value variable must match the type of the elements in the array. It then executes the code within the block that makes up the foreach loop body. The line System.Console.Write(value); simply prints out the value on the Console.

Note: foreach loop gives you readonly access to the array elements, so you can’t change the values. To modify the values, you need to use for loop.

int[] arrayValues = new int[3] { 1, 2, 3 };
foreach (var value in arrayValues)
         Console.WriteLine(value);

You get the following output when you execute the code.

Run Demo

OUTPUT

1
2
3

string[] Vegetables = new string[5] { "Carrot", "Cucumber", "Tomato", "Onion", "Green Pepper" };
foreach (var veg in Vegetables)
{
         Console.WriteLine(veg);
}

Run Demo

OUTPUT

Carrot
Cucumber
Tomato
Onion
Green Pepper


C# Reference | Microsoft Docs