Overview of Arrays in C#

Objective of the Module

  • Introduction
  • Arrays Overview
  • Declaration of Arrays
  • Reference Type
  • Array Exception Handling
  • Multi-Dimension Arrays

Introduction

Arrays are powerful data structures for solving many programming problems. You saw during the creation of variables of many types that they have one thing in common, they hold information about a single item, for instance an integer, float and string type and so on. So what is the solution if you need to manipulate sets of items? One solution would be to create a variable for each item in the set but again this leads to a different problem. How many variables do you need?

So in this situation Arrays provide mechanisms that solves problem posed by these questions. An array is a collection of related items, either value or reference type. In C# arrays are immutable such that the number of dimensions and size of the array are fixed.

Arrays Overview

An array contains zero or more items called elements. An array is an unordered sequence of elements. All the elements in an array areof the same type (unlike fields in a class that can be of different types). The elements of an array accessed using an integer index that always starts from zero. C# supports single-dimensional (vectors), multidimensional and jagged arrays.

Elements are identified by indexes relative to the beginning of the arrays. An index is also commonly called indices or subscripts and are placed inside the indexing operator ([]). Access to array elements is by their index value that ranges from 0 to (length-1).

Array Properties

  • The length cannot be changed once created.

  • Elements are initialized to default values.

  • Arrays are reference types and are instances of System.Array.

  • Their number of dimensions or ranks can be determined by the Rank property.

  • An array length can be determined by the GetLength() method or Length property.

Simple Arrays Example

In the following example, at line 10 we are declaring an Integer type array variable myArrays with length 5. Which means the myArrays variable can hold 5 integer elements. From line 15, we are accessing each element using a for loop and doing an even number of calculations over them. Finally at line 21, we are displaying each element.

  1. using System;  
  2.   
  3. namespace Arrays  
  4. {  
  5.     class Program  
  6.     {  
  7.         static void Main(string[] args)  
  8.         {  
  9.             // Integer type array with length 5( range 0 to 4)  
  10.             int[] myArrays = new int[5];  
  11.   
  12.            Console.WriteLine("Simple Array Example");  
  13.   
  14.             // Arrays inititalization  
  15.             for (int i = 0; i < myArrays.Length; i++)  
  16.             {  
  17.                 // Even number manipulation  
  18.                 myArrays[i] = i * 2;   
  19.   
  20.                 // print array  
  21.                 Console.WriteLine(myArrays[i]);    
  22.             }  
  23.   
  24.             Console.ReadKey();    
  25.         }  
  26.     }  

Once we compile this program it displays 5 even numbers on the screen. Because we have configured the arrays variable to hold up to 5 elements only as in the following.

Simple array output
                              Figure 1.1- Simple array output

Declaration Arrays

An array is a contiguous memory allocation of same-sized data type elements. After declaring an array, memory must be allocated to hold all the elements of the array. An array is a reference type, so memory on the heap must be allocated.

Array Declaration

                                                Figure 1.2- Array Declaration

The preceding figure shows the array declaration and allocation syntax for a single-dimension array having a specific type and length. The declaration begins with the array element type. The element of an array can be a value type or reference type. The element is followed by a set of empty brackets. Single-dimension arrays use one set of brackets. The element type, plus the brackets, yields an array type. This array type is followed by an identifier that declares the name of the array.

To actually allocate memory for an array, use the new operator followed by the type of elements the array can contain followed by the length of the array in brackets.

For example, the following line of code declares and allocates memory for a single-dimension array of integer having a length of 3.

  1. int[] myArrays = new int[3]; 

The following line of code would simply declare an array of floats:

  1. float[] myArrays; 

And this code would allocate memory (initialize) to hold 6 float values:

  1. myArrays=new float[6] ; 

The following line of code would simply declare an array of strings:

  1. String[] arry = new String[8];  

You can also assign values to every array element using an array initialize.

  1. int[] arry = new int[5] { 15, 3, 7, 8, 9 }; 

Example-Finding an Array type, Rank and Total elements;

The following example calculates an integer type array length, type and rank (dimension).

  1. using System;  
  2.   
  3. namespace Arrays  
  4. {  
  5.     class Program  
  6.     {  
  7.         static void Main(string[] args)  
  8.         {  
  9.             // Integer type array with length 5( range 0 to 4)  
  10.             int[] arry = new int[5];  
  11.   
  12.             Console.WriteLine("Type=" + arry.GetType());  
  13.             Console.WriteLine("Rank=" + arry.Rank);  
  14.             Console.WriteLine("Length=" + arry.Length);  
  15.   
  16.             Console.ReadKey();    
  17.         }  
  18.     }  

Vector Array using Literal Values

Up to this point you have seen how memory for an array can be allocated using the new operator. Another way to allocate memory for an array and initialize its elements at the same time is to specify the contents of an array using array literal values.

  1. int[] arry = {1,2,3,4,5}; 

The length of an array is determined by the number of literal values appearing in the declaration.

  1. string[] arry = {"A""J""A""Y"};  
  2.   
  3. bool[] arry = {truefalse}; 

Example-Concatenation of Two Strings

The following example shows the concatenation of two words.

  1. using System;  
  2.   
  3. namespace Arrays  
  4. {  
  5.     class Program  
  6.     {  
  7.         static void Main(string[] args)  
  8.         {  
  9.             // string type array with length 2( range 0 to 1)  
  10.             string[] arry = {"Barack" , "Obama"};  
  11.   
  12.             //string concatenation  
  13.             Console.WriteLine(arry[0] + " " + arry[1] );  
  14.               
  15.             Console.ReadKey();    
  16.         }  
  17.     }  

Example-Finding Largest Number in Range of Integers

The following first declares an integer type of array with length of 5 then it iterates through with all the elements to determine the largest number in the array via for loop. Meanwhile, it also checks all the values with the variable x. If the value of x is greater than each element then one by one it continues the loop, otherwise it changes the value of x by assigning the current element value. Finally it prints the largest values.

  1. using System;  
  2.   
  3. namespace Arrays  
  4. {  
  5.     class Program  
  6.     {  
  7.         static void Main(string[] args)  
  8.         {  
  9.             // Integer type array   
  10.             int[] arry = {5,3,7,8,9};  
  11.   
  12.             int x=0;  
  13.   
  14.             for (int i = 0; i < arry.Length; i++)  
  15.             {  
  16.   
  17.                 if (x > arry[i])  
  18.                 {  
  19.                    continue;  
  20.                 }  
  21.                 else  
  22.                 {  
  23.                     x = arry[i];  
  24.                 }  
  25.             }  
  26.               
  27.             Console.WriteLine("Largest Number=" + x);  
  28.               
  29.             Console.ReadKey();    
  30.         }  
  31.     }  

Reference Type

A Reference Type of an array can be implemented by creating a custom class. A variable of a reference type does not contain its data directly. However, you cannot change the value of the reference itself. Let's start with a Customer class with two constructors, the properties FirstName and LastName and an override of the ToString() method for concatenation of the two words. In the main class we create an array of Customer class objects with length 2 and finally print the FirstName and LastName via iterating the foreach loop as in the following:

  1. using System;  
  2.   
  3. namespace Arrays  
  4. {  
  5.     public class Customer  
  6.     {  
  7.         public Customer() { }  
  8.   
  9.         public Customer(string fname,string lname)  
  10.         {  
  11.             this.fname = fname;  
  12.             this.lname = lname;  
  13.         }  
  14.         private string fname;  
  15.         private string lname;  
  16.   
  17.         public string FirstName  
  18.         {  
  19.             get { return fname; }  
  20.             set { fname = value; }  
  21.         }  
  22.   
  23.         public string LastName  
  24.         {  
  25.             get { return lname; }  
  26.             set { lname = value; }  
  27.         }  
  28.         public override string ToString()  
  29.         {  
  30.             return fname + " " + lname;  
  31.         }  
  32.     }  
  33.     class Program  
  34.     {  
  35.         static void Main(string[] args)  
  36.         {  
  37.             Customer[] obj = new Customer[2];  
  38.             obj[0] = new Customer("ajay","yadav");  
  39.             obj[1] = new Customer("tom","hanks");  
  40.   
  41.             foreach(Customer i in obj)  
  42.             {  
  43.                 Console.WriteLine(i.ToString());  
  44.             }  
  45.             Console.ReadKey();  
  46.         }  
  47.     }  

Array Exception Handling

Sometimes we unintentionally create glitches in the code pertaining to an array index range. For example in the following program we are calculating the sum of five numbers. So at line 5, in the for loop we are putting an equal sign in the condition. In that case the loop will execute 6 times rather than 5 times; this eventually generates an Index out of range error.

However due to evading such coding glitches we are putting the significant code into the try block and using a catch block we are flashing an alert message for index out of range as in the following:

error

Multi-Dimension Arrays

Ordinary arrays are indexed by a single integer. A multidimensional array is indexed by two or more integers. Declaring a 2-dimensional array with C# is done by putting a semicolon inside the brackets. The array is initialized by specifying the size of every dimension. Then the array elements can be accessed using two integers with the indexer.

Here we are declaring a 2D array that has two rows and two columns and assigning them values:

  1. // 2D integer type array  
  2. int[,] dArray = new int[2,2];  
  3. dArray[0, 0] = 1;  
  4. dArray[0, 1] = 2;  
  5. dArray[1, 0] = 3;  
  6. dArray[1, 1] = 4; 

A 2D array can be visualized as a grid or matrix comprised of rows and columns. The following table depicts a 2 X 2 dimension array with values in the corresponding rows and columns as in the following.

2D array
You can also initialize the 2D array using an array indexer if you know the value for the elements in advance as in the following:

  1. // 2D integer type array  
  2. int[,] dArray ={  
  3.    {1,2,3},  
  4.    {4,5,6}  
  5. }; 

The following program generates a double-dimension array grid by providing the values as well as it calculate the total number of elements with ranks:

  1. using System;  
  2.   
  3. namespace Arrays  
  4. {  
  5.     class Program  
  6.     {  
  7.         static void Main(string[] args)  
  8.         {  
  9.             Console.WriteLine("Enter the Rank::");  
  10.             int row = Int32.Parse(Console.ReadLine());  
  11.             int cols = Int32.Parse(Console.ReadLine());  
  12.             Console.WriteLine("__________________________");  
  13.             int[,] doubleArray = new int[row, cols];  
  14.   
  15.             for (int i = 0, j = 1; i < doubleArray.GetLength(0); i++)  
  16.             {  
  17.                 for (int k = 0; k < doubleArray.GetLength(1); k++)  
  18.                 {  
  19.                     doubleArray[i, k] = j++;  
  20.                     Console.Write("{0:D3} ", doubleArray[i, k]);  
  21.                 }  
  22.                 Console.WriteLine();  
  23.             }  
  24.   
  25.             Console.WriteLine();  
  26.             Console.WriteLine("Rank=" + doubleArray.Rank);  
  27.             Console.WriteLine("Elements=" + doubleArray.Length);  
  28.   
  29.             Console.ReadKey();  
  30.         }  
  31.     }  

When you compile this program, it asks you to enter the dimension (rank) of the array and then it displays the values in the form of a matrix as in the following:

2D Array image
                           Figure 1.3- 2D Array

Rectangular arrays can be initialized using the literal values in an array initialization expression as in the following.

  1. using System;  
  2.   
  3. namespace Arrays  
  4. {  
  5.     class Program  
  6.     {  
  7.         static void Main(string[] args)  
  8.         {  
  9.             char[,] doubleArray = {  
  10.                                      {'A','B','C'},  
  11.                                      {'D','E','F'},  
  12.                                      {'G','H','I'}  
  13.                                  };  
  14.   
  15.             for (int i = 0; i < doubleArray.GetLength(0); i++)  
  16.             {  
  17.                 for (int k = 0; k < doubleArray.GetLength(1); k++)  
  18.                 {  
  19.                     Console.Write(doubleArray[i, k] + " ");  
  20.                 }  
  21.                 Console.WriteLine();  
  22.             }  
  23.   
  24.             Console.WriteLine();  
  25.             Console.WriteLine("Rank=" + doubleArray.Rank);  
  26.             Console.WriteLine("Elements=" + doubleArray.Length);  
  27.   
  28.             Console.ReadKey();  
  29.         }  
  30.     }  

The output of the preceding program is as in the following:

Literal 2D Array
                       Figure 1.4- Literal 2D Array