C# Array

C# Array

1 - Introduction to the C# array

Like other programming languages, array in C# is a group of similar types of elements that have contiguous memory location. In C#, array is an object of base type System.Array. In C#, array index starts from 0. We can store only fixed set of elements in C# array.

C# array - XDevSpace
  • An array stores a fixed number of elements of the same type. 
  • To declare an array variable, you use square brackets [] after the element’s type.

 

For example:

char[] letterArray = new char[5]; // Declare an array of 5 characters

We can use square brackets [] to index the array, and access a particular element by position:

letterArray[0] = 'a'; 
letterArray[1] = 'e'; 
letterArray[2] = 'i'; 
letterArray[3] = 'o'; 
letterArray[4] = 'u'; 
Console.WriteLine (letterArray[1]); // e 

We can use a for loop statement to iterate through each element in the array.

for (int i = 0; i < letterArray.Length; i++) {
    Console.Write (letterArray[i]); // aeiou 
}

The Length property of an array returns the number of elements in the array.

Once an array has been created, its length cannot be changed.

An array initialization expression can declare and populate an array in a single step:

char[] letterArray = new char[] {'a','e','i','o','u'}; 

or simply:

char[] letterArray = {'a','e','i','o','u'};

All arrays inherit from the System.Array class, providing common services for all arrays.

 

2 - C# Array Declaration

To declare an array in C#, you can use the following syntax:

datatype[] arrayName;

where,

  • datatype is used to specify the type of elements in the array.
  • [ ] specifies the rank of the array. The rank specifies the size of the array.
  • arrayName specifies the name of the array.

For example:

double[] balance;

 

3 - C# Array Initialization

Declaring an array in C# does not initialize the array in the memory. When the array variable is initialized, you can assign values to the array.

Array is a reference type, so you need to use the new keyword to create an instance of the array. 

For example:

double[] balance = new double[10];

 

4 - C# Late Initialization

It is not necessary to declare and initialize an array in a single statement. You can first declare an array then initialize it later on using the new operator.

For example:

int[] evenNums;

evenNums = new int[5];
// or
evenNums = new int[]{ 2, 4, 6, 8, 10 };

 

5 - C# Assigning Values to an Array

You can assign values to individual array elements, by using the index number, like:

double[] balance = new double[10];
balance[0] = 4500.0;

You can assign values to the array at the time of declaration, as shown:You can assign values to the array at the time of declaration, as shown:

double[] balance = { 2340.0, 4523.69, 3421.0};

You can also create and initialize an array, as shown:

int [] marks = new int[5]  { 99,  98, 92, 97, 95};

You may also omit the size of the array, as shown:

int [] marks = new int[]  { 99,  98, 92, 97, 95};

You can copy an array variable into another target array variable. In such case, both the target and source point to the same memory location:

int [] marks = new int[]  { 99,  98, 92, 97, 95};
int[] score = marks;

When you create an array, C# compiler implicitly initializes each array element to a default value depending on the array type. 

For example: for an int array all elements are initialized to 0.

 

6 - C# Accessing Array Elements

An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets [] after the name of the array

An index is a number associated with each array element, starting with index 0 and ending with array size -1.

For example:

double salary = balance[9];

The following example, demonstrates the above-mentioned concepts declaration, assignment, and accessing arrays:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] n = new int[10]; /* n is an array of 10 integers */
            int i, j;

            /* initialize elements of array n */
            for (i = 0; i < 10; i++)
            {
                n[i] = i + 100;
            }

            /* output each array element's value */
            for (j = 0; j < 10; j++)
            {
                Console.WriteLine("Element[{0}] = {1}", j, n[j]);
            }

            Console.WriteLine("Press Enter Key to Exit..");
            Console.ReadLine();
        }
    }
}

Output:

When the above code is compiled and executed, it produces the following result:

C# Accessing Array Elements - XDevSpace

Example: Access Array Elements using Indexes

The following example add/update and retrieve array elements using indexes.

int[] evenNums = new int[5];
evenNums[0] = 2;
evenNums[1] = 4;
//evenNums[6] = 12;  //Throws run-time exception IndexOutOfRange

Console.WriteLine(evenNums[0]);  //prints 2
Console.WriteLine(evenNums[1]);  //prints 4

Note that trying to add more elements than its specified size will result in IndexOutOfRangeException.

 

7 - C# Accessing Array using foreach Loop

In the previous example, we used a for loop for accessing each array element. You can also use a foreach statement to iterate through an array.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] n = new int[10]; /* n is an array of 10 integers */

            /* initialize elements of array n */
            for (int i = 0; i < 10; i++)
            {
                n[i] = i + 100;
            }

            /* output each array element's value */
            foreach (int j in n)
            {
                int i = j - 100;
                Console.WriteLine("Element[{0}] = {1}", i, j);
                i++;
            }

            Console.WriteLine("Press Enter Key to Exit..");
            Console.ReadLine();
        }
    }
}

Output:

When the above code is compiled and executed, it produces the following result:

C# Using the foreach Loop - XDevSpace

8 - C# Access Array Elements with For Loop

In c#, by using for loop we can iterate through array elements and access the values of an array with length property.

Following is the example of accessing array elements using for loop in the c# programming language:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] array = new int[5] { 1, 2, 3, 4, 5 };
            for (int i = 0; i < array.Length; i++)
            {
                Console.WriteLine(array[i]);
            }

            Console.WriteLine("Press Enter Key to Exit..");
            Console.ReadLine();
        }
    }
}

If you observe the above example, we are looping through array elements with for loop to access array elements based on our requirements.

When we execute the above c# program, we will get the result below:

C# Access Array Elements with For Loop - XDevSpace

9 - C# Value types versus reference types

When the element type is a value type, each element value is allocated as part of the array.

For example:

struct Point { 
  public int X, Y; 
} 

Point[] a = new Point[1000]; 
int x = a[500].X; // 0 

If Point is a class, creating the array would have only allocated 10 null references:

class Point { 
  public int X, Y; 
} 

Point[] a = new Point[10]; 
int x = a[5].X; // Runtime error, NullReferenceException 

To avoid this error, explicitly instantiate Point value after instantiating the array:

Point[] a = new Point[10]; 
for (int i = 0; i < a.Length; i++){ // Iterate i from 0 to 9
    a[i] = new Point();             // Set array element i with new point 
}

An array itself is always a reference type object, regardless of the element type.

For instance, the following is legal:

int[] myArray = null;

 

10 - LINQ Methods

All the arrays in C# are derived from an abstract base class System.Array.

The Array class implements the IEnumerable interface, so you can LINQ extension methods such as Max(), Min(), Sum(), reverse(), etc. See the list of all extension methods here.

Example: LINQ Methods

int[] nums = new int[5]{ 10, 15, 16, 8, 6 };

nums.Max(); // returns 16
nums.Min(); // returns 6
nums.Sum(); // returns 55
nums.Average(); // returns 55

The System.Array class also includes methods for creating, manipulating, searching, and sorting arrays. See list of all Array methods here.

Example: Array Methods

int[] nums = new int[5]{ 10, 15, 16, 8, 6 };

Array.Sort(nums); // sorts array 
Array.Reverse(nums); // sorts array in descending order
Array.ForEach(nums, n => Console.WriteLine(n)); // iterates array
Array.BinarySearch(nums, 5);// binary search 

 

11 - C# Passing Array as Argument

An array can be passed as an argument to a method parameter. Arrays are reference types, so the method can change the value of the array elements.

Example: Passing Array as Argument

public static void Main(){
            int[] nums = { 1, 2, 3, 4, 5 };

    UpdateArray(nums); 

            foreach(var item in nums)
            Console.WriteLine(item);   
}
                    
public static void UpdateArray(int[] arr)
{
            for(int i = 0; i < arr.Length; i++)
        arr[i] = arr[i] + 10;   
}

 

12 - C# Getting the Length of an Array

The length of a C# array may be obtained by accessing the Length property of the array in question. 

For example:

string[] myColors = {"red", "green", "yellow", "orange", "blue"};

System.Console.WriteLine ("Length of array = ", myColors.Length);

In the case of a multidimensional array, the Length property will contain the entire length of the array (including all dimensions). For example, our books two-dimensional array will have a length of 9.

 

13 - Sorting and Manipulating C# Arrays

A number of methods are available as part of the System.Array package for the purpose of manipulating arrays.

An array may be sorted using the System.Array.Sort() method:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] myColors = { "red", "green", "yellow", "orange", "blue" };

            Array.Sort(myColors);

            for (int i = 0; i < myColors.Length; i++)
            {
                Console.WriteLine(myColors[i]);
            }

            Console.WriteLine("Press Enter Key to Exit..");
            Console.ReadLine();
        }
    }
}

The above example will sort the elements of the myColors array into alphabetical order:

Sorting and Manipulating C# Arrays - XDevSpace

The order of the elements may subsequently be reversed using the System.Array.Reverse() method:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] myColors = { "red", "green", "yellow", "orange", "blue" };

            Array.Reverse(myColors);

            for (int i = 0; i < myColors.Length; i++)
            {
                Console.WriteLine(myColors[i]);
            }

            Console.WriteLine("Press Enter Key to Exit..");
            Console.ReadLine();
        }
    }
}

Resulting in the following output:

Sorting and Manipulating C# Arrays

The values in an array may be cleared using the System.Array.Clear() method. This method clears each item in an array to the default value for the type (false for boolean, 0 for numeric and null for a string).

 

14 - Advantages of C# Array

  • Code Optimization (less code)
  • Random Access
  • Easy to traverse data
  • Easy to manipulate data
  • Easy to sort data etc.

 

15 - Disadvantages of C# Array

  • Fixed size

 

16 - C# Array Types

There are 3 types of arrays in C# programming:

  • Single Dimensional Array
  • Multidimensional Array
  • Jagged Array

 

17 - C# Single Dimensional Array

To create single dimensional array, you need to use square brackets [] after the type.

int[] arr = new int[5];//creating array  

You cannot place square brackets after the identifier.

int arr[] = new int[5];//compile time error  

Let's see a simple example of C# array, where we are going to declare, initialize and traverse array:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] arr = new int[5];//creating array  
            arr[0] = 10;//initializing array  
            arr[2] = 20;
            arr[4] = 30;

            //traversing array  
            for (int i = 0; i < arr.Length; i++)
            {
                Console.WriteLine(arr[i]);
            }

            Console.WriteLine("Press Enter Key to Exit..");
            Console.ReadLine();
        }
    }
}

Output:

C# Single Dimensional Array - XDevSpace

18 - C# Array Example: Declaration and Initialization at same time

There are 3 ways to initialize array at the time of declaration.

int[] arr = new int[5]{ 10, 20, 30, 40, 50 };

We can omit the size of array.

int[] arr = new int[]{ 10, 20, 30, 40, 50 };  

We can omit the new operator also.

int[] arr = { 10, 20, 30, 40, 50 };  

Let's see the example of array where we are declaring and initializing array at the same time:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] arr = { 10, 20, 30, 40, 50 };//Declaration and Initialization of array  

            //traversing array  
            for (int i = 0; i < arr.Length; i++)
            {
                Console.WriteLine(arr[i]);
            }

            Console.WriteLine("Press Enter Key to Exit..");
            Console.ReadLine();
        }
    }
}

Output:

C# Array Example: Declaration and Initialization at same time

 

19 - C# Array Example: Traversal using foreach loop

We can also traverse the array elements using foreach loop. It returns array element one by one.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] arr = { 10, 20, 30, 40, 50 };//creating and initializing array  

            //traversing array  
            foreach (int i in arr)
            {
                Console.WriteLine(i);
            }

            Console.WriteLine("Press Enter Key to Exit..");
            Console.ReadLine();
        }
    }
}

Output:

C# Array Example: Traversal using foreach loop - XDevSpace