Array in C#

By   Calendar icon Jan 10, 2020   Level 1 icon

Description:

In this article, we explain how to use C# arrays and give some examples. An array is a sequence of objects, each element of which is accessible through an index.

Preferencesoft

Tags: C#

An array is a sequence of consecutive elements, of the same type (or class).
The elements of an array are numbered from 0.
To access an item, one uses an integer index and the following syntax with square brackets:

<element_type>[<index>]

gives the element of number index.

elements

The elements in an array are numbered variables. In the previous figure a[0] represents the first element. On the other hand, a[0], ..., a[7] are considered as variables.

Arrays declaration

Reference to an array

An array without element is declared as follows:

<element_type>[] <array_name>;

In this case, the array_name variable is a null reference. But after declaring it, it is possible to assign an array of elements of the type element_type.

Example 1

using System;

public class Program
{

    public static void Main()
    {
        double[] arr;
        Console.WriteLine(arr[0]); // error
        // use of unassigned local variable 'arr'
    }
}

Initialized array

We can place items in an array when it is defined.

We can change the value of each item in the array, but it is impossible to resize it except by reassigning a new array to the variable.

<element_type>[] <array_name> = new <element_type>[<array_size>];
<element_type>[] <array_name> = {<value_1>, <value_2>, ..., <value_N> };
<element_type>[] <array_name> = new <element_type>[]{<value_1>, <value_2>, ..., <value_N> };

Example 1

using System;

public class Program
{

    public static void Main()
    {
        int[] a = new int[4]; // create an array of size 4
        a[0] = 480;
        a[3] = a[0];
        Console.WriteLine("a[3]={0}", a[3]);
        Console.WriteLine("a[0]={0}", a[0]);
    }
}

Example 2

using System;

public class Program
{

    public static void Main()
    {
        byte[] a = { 128, 1, 0, 0xFF }; // create an initialized array
        Console.WriteLine("a[3]={0}", a[3]);
    }
}

Length of an array

Example 1
Let us write a program that displays the length of an array and the last element.

using System;

public class Program
{

    public static void Main()
    {
        string[] students = { "John", "Kate", "Eric", "Helen" }; // create a string array
        Console.WriteLine("Number of students: {0}", students.Length);
        Console.WriteLine("Last student: {0}", students[students.Length - 1]);
    }
}

Searching for an item in an array

Example 1
Let us declare an array containing the 25 first prime numbers.
Let us write a program that asks the user for an integer less than 100 and that displays, depending on the case, whether it is prime or not.

using System;

public class Program
{
    public static void Main()
    {
        int[] primeNumbers = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
                              43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97};
        Console.WriteLine("Enter an integer less than 100");
        int i = int.Parse(Console.ReadLine());
        if (Array.IndexOf(primeNumbers, i) >= 0)
            Console.WriteLine("{0} is prime", i);
        else
            Console.WriteLine("{0} is not prime", i);
    }
}

Iterating through an array

The primary purpose of an array is to be able to access the elements of an array by index, to browse them to perform operations on some, etc.

Any loop statement can step through the elements of an array. Note that the foreach statement does not allow you to modify any element of an array.

Example 1
Let us write a program that uses the foreach statement, to calculate the sum of the actual numbers in a table.

using System;

public class Program
{
    public static void Main()
    {
        double[] arr;
        Console.WriteLine("Enter a positive integer ");
        int len = int.Parse(Console.ReadLine());
        arr = new double[len];
        Random rnd = new Random();
        for (int i = 0; i < len; i++) arr[i] = rnd.Next(11);
        foreach (double e in arr)
            Console.Write("{0}  ", e);
        double sum = 0;
        foreach (double e in arr)
            sum += e;
        Console.Write("Sum={0}", sum);
    }
}

Array of object

Example 1

using System;

public class Program
{
    class Elements
    {
        public string name = "";
        public int age = 0;
    }
    public static void Main()
    {
        Elements[] arr = new Elements[3] { new Elements(),
            new Elements(), new Elements() };
        arr[0].name = "John";
        arr[0].age = 22;
        arr[1].name = "Kate";
        arr[1].age = 40;
        Console.WriteLine("{0}", arr[1].name);
    }
}

Example 2

using System;

public class Program
{
    class Elements
    {
        int _element = 0;
        public Elements(int val)
        {
            _element = val;
        }
        public int Val
        {
            get { return _element; }
        }
    }
    public static void Main()
    {
        Elements[] arr = new Elements[2] { new Elements(45), new Elements(8) };
        Console.WriteLine("{0}", arr[1].Val);
    }
}

CSharp