| by Arround The Web | No comments

How to Initialize and Manipulate a C# Array

In this comprehensive tutorial, we will teach you how to work with arrays in the C# programming language. We will start from the basics and learn how to initialize a new array, access the array elements, and more.

What Is an Array?

Let us start with the basics and define an array. In C#, an array refers to a fixed-size, strongly-type collection of elements of the same data type. Unlike the scalar variables that can hold a single element at a single time, arrays allows us to store multiple items.

In array, we can only store the elements of the same type. For example, we can have an array of strings, ints, doubles, etc. Each element in an array is referred to by an index. Array indexes in C# are zero-based which means that the first element in the array is at index 0.

It is good to keep in mind that arrays in C# are stored in contiguous memory blocks.

Declare an Array

In C#, array declaration is comprised of two main parts. The first part is the type of the array, the second is the array name.

The type of the array is used to define the data type that we store in the array. For example, we can define an array as “int” to store the integers, “float” to store floating point values, etc.

We also include a pair of square brackets to indicate the definition that represents an array.

The following shows the syntax of declaring an array in C#:

dataType[] arrayName;

For example, to declare an array that stores the integer values, we can run the following code:

int[] newArray;

C# also allows to declare a new array using the traditional form. The syntax is as follows:

dataType[] arrayName = new dataType[arraySize];

In this case, we start with the data type of the array followed by the array name. Next, we use the assignment operator and the new keyword to define the type of the array and the number of elements that we wish to store in the array.

For example, to declare and initialize an integer array that can store five elements, we can run the query as follows:

int[] newArray = new int[5];

In the given example, we declared a new int array called “newArray” of size 5.

Initialize the Arrays

Array initialization refers to the process of setting the initial values of the array during its declaration. Array initialization can involve setting the size of the array and assigning the initial values to the elements, either individually or as a group.

Let us explore the various methods to initialize an array in C#.

Assignment Initialization

The first method of initializing a C# array is using the element index. Consider an example as follows:

using System;
class Program
{
    static void Main()
    {
        // Declare an integer array of size 5
        int[] numbers = new int[5];

        // Access and assign each element in the array
        numbers[0] = 1;
        numbers[1] = 2;
        numbers[2] = 3;
        numbers[3] = 4;
        numbers[4] = 5;

        Console.WriteLine("Array elements:");
        // print all array elements
        for (int i = 0; i < numbers.Length; i++)
        {
            Console.WriteLine("Element at index " + i + ": " + numbers[i]);
        }
    }
}

Let us explain the given code.

In the given example, we start by declaring an array which holds five integer values.

We then initialize the array with some values. This method of array initialization is also known as assignment initialize as it involves us to manually assign a value to each array element.

As you can see from the previous example, we use the square brackets to access the element index. For example, to access the element at the first position, we use the arrayName[0].

Once we assigned the values to all elements in the array, we use a classic “for” loop to iterate over all the elements of the array and print them to the console.

An array in C# has a “Length” property which returns the number of elements in the array. Since indexing in C# starts at 0, the length is equal to length – 1.

Output:

Array elements:
Element at index 0: 1
Element at index 1: 2
Element at index 2: 3
Element at index 3: 4
Element at index 4: 5

One Liner

The second and most common method of array initialization in C# involves the declaration and assignment operation. This means that we can just combine the array declaration and assignment in a single line as demonstrated in the following:

using System;
class Program
{
    static void Main()
    {
        // Declare an integer array of size 5
        int[] numbers = new int[5] {1,2,3,4,5};

        Console.WriteLine("Array elements:");
        // print all array elements
        for (int i = 0; i < numbers.Length; i++)
        {
            Console.WriteLine("Element at index " + i + ": " + numbers[i]);
        }
    }
}

As you can notice, the previous code removes the need of manually accessing each index and assigning a new value to it.

In this case, we declare a new array and set the values all in the same line.

Using the C# Array.Fill

C# also provides us with the Fill() method which allows us to populate the whole array with a given value.

Consider the following example:

using System;
class Program
{
    static void Main()
    {
        // Declare an integer array of size 5
        int[] numbers = new int[5];

        // Initialize the entire array with a specific value
        Array.Fill(numbers, 42);

        Console.WriteLine("Array elements after initialization:");
        // Print all array elements
        for (int i = 0; i < numbers.Length; i++)
        {
            Console.WriteLine("Element at index " + i + ": " + numbers[i]);
        }
    }
}

In the given example, we start by declaring an array of integers called “numbers” with the size of 5.

We then use the Array.Fill method to initialize the entire array with a single value which, in this case, is the number 42.

The Array.Fill method follows the example syntax as follows:

Array.Full(array, value)

Once we initialize the array, we print all the elements in the array using a classic “for” loop. The resulting output is as follows:

Element at index 0: 42
Element at index 1: 42
Element at index 2: 42
Element at index 3: 42
Element at index 4: 42

As you can notice, all the elements in the array contain the same value.

Access the Array Elements

Once we created an array, we can access its elements using their index. We start with the array name followed by the index that we wish to access inside a pair of square brackets.

The syntax is as follows:

arrayName[index]

For example, suppose we have an array of strings and we wish to print them all to the console. We can run the code as follows:

using System;
class Program
{
    static void Main()
    {
        string[] databases = { "MySQL", "PostgreSQL", "SQLite", "Microsoft SQL Server", "Oracle Database" };

        Console.WriteLine("Popular Databases:");
        foreach (string database in databases)
        {
            Console.WriteLine(database);
        }
    }
}

In the given example, we start by defining an array of databases and assigning the values to the array.

We then use a “for” loop to iterate over the array and access each element using its index on each iteration.

The resulting output is as follows:

Popular Databases:
MySQL
PostgreSQL
SQLite
Microsoft SQL Server
Oracle Database

Modify the Elements

In some cases, you may need to modify the element of an array after declaration. Luckily, the arrays in C# are not immutable. Hence, we can easily set a new value of an array using the assignment operator as follows:

using System;

class Program
{
    static void Main()
    {
        int[] numbers = { 1, 2, 3, 4, 5 };
        foreach (int item in numbers)
        {
            Console.WriteLine(item);
        }
        numbers[2] = 10;
        foreach (int item in numbers)
        {
            Console.WriteLine(item);
        }
    }
}

In the given example, we start by declaring and initializing an integer array called “numbers” with the values of 1, 2, 3, 4, 5.

We then print the original array before making any modifications.

Lastly, we modify the element of the array at index 2 by setting its value to 10 and print the new array.

The resulting value is as follows:

1 2 3 4 5
1 2 10 4 5

You might notice that the second value in the array has changed to reflect the modifications.

Array Slicing

Array slicing refers to the process of creating a new array that contains a subset of the elements of an existing array. Slicing allows us to extract a contiguous block of an original array without modifying the original array.

In C# 8.0 and above, we can perform the array slicing using the “..” operator. This simplifies the process of specifying the range of elements in the array as follows:

using System;

class Program
{
    static void Main()
    {
        int[] numbers = { 1, 2, 3, 4, 5 };
        // first 3 elements
        int[] sub = numbers[..3];
        // last three elements
        int[] last = numbers[3..];
        // between
        int[] between = numbers[1..3];
    }
}

The previous code is comprised of three main parts as explained in the following:

  • int[] sub = numbers[..3]; – This creates a new array called “sub” which contains the first three elements of the “numbers” array.
  • int[] last = numbers[3..]; – This block creates a new array called “last” which contains the last three elements of the “numbers” array.
  • int[] between = numbers[1..3]; – This block creates a new array called “between” which contains the elements at index 1 and 2 from the “numbers” array.

Multidimensional Arrays

C# also supports multidimensional arrays. If you are not familiar, multidimensional arrays refer to an array of more than one dimension or rank.

To declare and initialize a multidimensional array in C#, we can run the following code:

using System;
class Program
{
    static void Main()
    {
        // Declare and initialize a 2D array (3x3 matrix)
        int[,] matrix = new int[3, 3] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };

    }
}

In the given example, we define a 2D array as a 3×3 matrix.

We can also declare a rectangular array as shown in the following. A rectangular array is an array where all the rows have the same number of columns. An example is as follows:

int[,] rect = new int[2, 4] { { 1, 2, 3, 4 }, { 5, 6, 7, 8 } };

Jagged Array

In C#, we can also define a jagged array which is an array where each row can have a different number of columns.

An example is as follows:

int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[] { 1, 2, 3 };
jaggedArray[1] = new int[] { 4, 5 };
jaggedArray[2] = new int[] { 6, 7, 8, 9 };

All the given demonstrations are examples of the value jagged arrays in C#.

Conclusion

In this comprehensive tutorial, we walked you through all the most fundamental and useful features of working with and manipulating the arrays in C#.

Share Button

Source: linuxhint.com

Leave a Reply