Arrays in C# Language

In this article I will explain you about Arrays in C#.


This article has been excerpted from book "The Complete Visual C# Programmer's Guide from the Authors of C# Corner".

Arrays

An array in C# is simply a set of sequential memory locations that can be accessed using either indices or references. A mechanism in C# prevents a program from writing outside the bounds of an array and destroying the contents of memory in the process: The declaration of an array simply sets aside the requisite block of memory and treats the name of the array as a synonym for the address of the block's beginning.

On our behalf, .NET Framework handles memory allocation behind the scenes. Arrays can be multidimensional, but their elements must be of the same base type. Arrays can store integers, strings, and any other type of object, including references and other arrays.

Arrays and Array Initializations

In C#, before using an array, you must declare it, providing two important pieces of information:

  • The name of the array
  • The type of data to be stored in it

Arrays may be declared in C# using the format below:

            int[] myArray;


As with other objects in C#, the declaration does not allocate memory for the array data but rather allocates memory for a reference to the array. Memory to contain the array data must be allocated from dynamic memory using statements such as the one below:


            int[] myArray = new int[15];


C# saves space until you explicitly assign a value to a reference type. For value types, however, the space is allocated immediately (see the example in the "System.Array Class" section).

The two statements above simultaneously declare the name of the array and cause memory to be allocated to contain it. The references are allocated but do not refer to anything until the array is actually assigned data.

It is not necessary, however, to combine these two processes. You can execute one statement to declare the array and another statement to allocate the memory:


            int[] myArray;
            // some code
            myArray = new int[25];


Causing memory to be set aside to contain the array data is commonly referred to as instantiating the array object—or creating an instance of the array object. If you prefer to declare and instantiate the array at different points in your program, you can use the syntax above.

This pattern is very similar to the declaration and instantiation of all objects in C#. This is the general syntax for declaring and instantiating an array:


            typeOfElements[] nameOfArray = new typeOfElements[sizeOfArray];        


Having instantiated an array in C#, you can access the elements of the array using index syntax similar to C++ and many other languages:


            myArray[5] = 6;
            myVar = myArray[5];


As in C++, array indices in C# always begin with 0.

The following code fragment illustrates another interesting aspect of arrays in C#:


            for (int cnt = 0; cnt < myArray.Length; cnt++)
                myArray[j] = j;


All array objects in C# have a Length property that can be accessed to determine the number of elements stored in the array.

Single–Dimensional Arrays

A single-dimensional array of size N has elements ranging from 0 to N–1 subscripts:


            int[] myIntArray = new int[5] { 5, 4, 3, 2, 1 };
            // or
            Array myArr = Array.CreateInstance(typeof(int), 5);


Listing 20.1 illustrates the use of single-dimensional arrays.

Listing 20.1: Outputting an array of strings to the Console


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

namespace
array
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter a sentence");
            String str1 = Console.ReadLine();
            Console.WriteLine("");

            //Iterate through the items of array args using foreach

            foreach (char s in str1)
            {
                Console.WriteLine(s);
            }

            Console.WriteLine("");

            //Declare array strNames
            string[] strNames = { "Ahmet", "Mustafa", "Mehmet", "Mahmut" };

            //Iterate through the items of array strNames
            for (int i = 0; i < strNames.Length; i++)
            {
                Console.WriteLine("strNames[{0}] = {1}", i, strNames[i]);
            }
        }
    }
}


Multidimensional Arrays

A multidimensional array of dimension n is a collection of items accessed via n subscript expressions. It can be declared with a different notation but in the same way as single-dimensional arrays, as shown in Listing 20.2.

Listing 20.2: Creating and Assigning values to Multidimensional Arrays


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

namespace
array
{
    class Program
    {
        static void Main(string[] args)
        {

            // simply like below
            // 3*2 member two-dimensional arrays
            int[,] intCount = new int[,] { { 1, 2, 3 }, { 4, 5, 6 } };

            // 1*3 member three-dimesional arrays
            int[, ,] intDec = new int[10, 20, 30];

            //or
            // Create and initialize a new three-dimensional array instance of type int
            Array myArr = Array.CreateInstance(typeof(int), 2, 3, 4);
            for (int i = myArr.GetLowerBound(0); i <= myArr.GetUpperBound(0); i++)
                for (int j = myArr.GetLowerBound(1); j <= myArr.GetUpperBound(1); j++)
                    for (int k = myArr.GetLowerBound(2); k <= myArr.GetUpperBound(2); k++)
                    {
                        myArr.SetValue((i * i) + (j * j) + k, i, j, k);
                    }
        }
    }
}


Listing 20.3 provides another example of multidimensional arrays that incorporates an enumerator class.

Listing 20.3: Multidimensional Arrays using an Enumerator


// array example - multidimensional

using
System;
public
class ArrayMembers
{
    public static void Main()
    {
        int[,] myIntArray = new int[,] { { 1, 2, 3 }, { 4, 5, 6 } };
        int i = 0;
        Console.WriteLine("myIntArray.GetUpperBound(0):" +
        myIntArray.GetUpperBound(0));
        Console.WriteLine("myIntArray.GetUpperBound(1):" +
        myIntArray.GetUpperBound(1));
        System.Collections.IEnumerator myEnumerator = myIntArray.GetEnumerator();
        int cols = myIntArray.GetLength(myIntArray.Rank - 1);

        while (myEnumerator.MoveNext())
        {
            if (i < cols)
            {
                i++;
            }
            else
            {
                Console.WriteLine();
                i = 1;
            }

            Console.Write("\t{0}", myEnumerator.Current);
        }
        Console.WriteLine();
    }
}


Rectangular Arrays

Rectangular arrays may be single-dimensional or multidimensional but always have a rectangular shape. Rectangular means that the length of each subarray in the same dimension is the same length.

Single-dimensional rectangular arrays are declared this way:


        short[] shtEmpNo;
        int[] intSalary;


Multidimensional rectangular arrays are declared this way:


        // two-dimensional arrays of short short[,] shtEmpNo;
       
// three-dimensional arrays of int int[,,] intSalary;


This is the syntax for a rectangular array:


Element-type (int, short, long) Rank-specifiers ([], [,,]) Name (Arrays Name)


Array types are reference types, so the declaration of an array variable merely sets aside space for the reference to the array. Array instances are actually created via array initializers and array creation expressions, as shown in Listing 20.4.

Listing 20.4: Rectangular Array Creation


        // 5 member single-dimensional arrays intialized
        short[] shtEmpNo = new short[5];
        // 3 member single-dimensional arrays
        int[] intSlNo = new int[] { 1, 2, 3 };
        // 3*2 member two-dimensional arrays
        int[,] intCount = new int[,] { { 1, 2, 3 }, { 4, 5, 6 } };
        // 1*3 member three-dimesional arrays
        int[, ,] intDec = new int[10, 20, 30];


In fact, in all languages developed for the .NET Framework, rectangular arrays are zero-based arrays, as shown in Listings 20.5 and 20.6 which start assigning array values to elements indexed at zero.

Listing 20.5: Rectangular Arrays Are Zero-Subscript-Based


shtEmpNo[0] = 0;
shtEmpNo[1] = 0;
shtEmpNo[2] = 0;
shtEmpNo[3] = 0;
shtEmpNo[4] = 0;
intSlNo[0] = 1 , intSlNo[1] = 2 and intSlNo[2] = 3;
intCount[0,0] = 1, intCount[1,0] = 2, intCount[0,1] = 4 , intCount[2,2] = 6;
intDec[0,0,0] = 10 , intDec[0,0,2] = 30;


Listing 20.6: Rectangular Array Example


using
System;
class
MyClass
{
    static void Main()
    {
        int[] intDec = new int[5];
        for (int i = 0; i < intDec.Length; i++)
            intDec[i] = i * 10;
        for (int i = 0; i < intDec.Length; i++)
            Console.WriteLine("intDec[{0}] = {1}", i, intDec[i]);
    }
}


Jagged Arrays

Jagged arrays are arrays of arrays. The syntax for a jagged array uses the square brackets after the type declaration for each dimension of the array:


        // "jagged" array: array of (array of int)
        int[][] j2;
        // array of (array of (array of int))
        int[][][] j3;


Listing 20.7 compares rectangular and jagged arrays.

Listing 20.7: Rectangular and Jagged Arrays


        //single-dimensional rectangular arrays
        int[] r1 = new int[] { 1, 2, 3 };

        //two-dimensional rectangular arrays
        int[,] r2 = new int[,] { { 1, 2, 3 }, { 4, 5, 6 } };

        //three-dimesional rectangular arrays
        int[, ,] r3 = new int[10, 20, 30];

        //"jagged" array: array of (array of int)
        int[][] j2 = new int[3][];
        j2[0] = new int[] { 1, 2, 3 };
        j2[1] = new int[] { 1, 2, 3, 4, 5, 6 };
        j2[2] = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };


The code in Listing 20.7 includes various expressions for creating both rectangular and jagged arrays. The variables r1, r2, and r3 are rectangular arrays, and the variable j2 is a jagged array.

Rectangular arrays always have a rectangular shape. For example, the length of r3's three dimensions are 10, 20, and 30, and it is easy to see that this array contains 10 x 20 x 30 elements.

The variable j2 is a jagged array—an array of an array of integers, or a single-dimensional array of type int[]. Each of these int[] variables can be initialized individually, and this allows the array to take on a jagged shape. Listing 20.7 gives each of the int[] arrays a different length. Specifically, the length of j2[0] is 3, the length of j2[1] is 6, and the length of j2[2] is 9. Listing 20.8 illustrates how to create and loop through a jagged array.

Listing 20.8: Creating and Outputting Jagged Arrays

// Jagged Array example

using
System;

public
class MyArrayc2
{
    public static void Main()
    {
        int[][] JaggedArray = new int[4][];
        JaggedArray[0] = new int[3];
        JaggedArray[1] = new int[2];
        JaggedArray[2] = new int[5];
        JaggedArray[3] = new int[4];
        Console.WriteLine("Enter the numbers for Jagged Array");

        for (int i = 0; i < JaggedArray.Length; i++)
        {
            for (int x = 0; x < JaggedArray[i].Length; x++)
            {
                String st = Console.ReadLine();
                int num = Int32.Parse(st);
                JaggedArray[i][x] = num;
            }
        }

        Console.WriteLine("");
        Console.WriteLine("Printing the Elements");

        for (int x = 0; x < JaggedArray.Length; x++)
        {
            for (int y = 0; y < JaggedArray[x].Length; y++)
            {
                Console.Write(JaggedArray[x][y]);
                Console.Write("\0");
            }

            Console.WriteLine("");
        }
    }
}


Conclusion

Hope this article would have helped you in understanding Arrays in C#. See other articles on the website on .NET and C#.

visual C-sharp.jpg The Complete Visual C# Programmer's Guide covers most of the major components that make up C# and the .net environment. The book is geared toward the intermediate programmer, but contains enough material to satisfy the advanced developer.