Arrays in C#


What is array

 

Array is a type that holds multiple variables of one type, allowing index access to the individual value.

 

An array is a series of elements of the same type placed in contiguous memory locations that can be individually referenced by adding an index to a unique identifier.

 

An array in .NET is created from Array base class. Array is a reference type because it is created from array class. The base class for arrays in C# is the System.Array class.

 

Array is fixed type. You can create array of primitive and non-primitive types. Array base address is stored in stack and array is kept in heap memory.

 

System.Array is the abstract base type of all array types. Array type can't be inherited. Array can't be extended. There size is fixed. Private constructor and inner class is use to create it.


Type of Arrays in C#.NET
 

  1. Single-dimensional arrays
  2. Multidimensional arrays (rectangular arrays)
  3. Jagged Arrays (array-of-arrays)
  4. Mixed Arrays

Single Dimensional Array

 

Single-dimensional arrays are the simplest form of arrays. These types of arrays are used to store number of items of a predefined type. All items in a single dimension array are stored in a row starting from 0 to the size of array - 1.

 

Single Dimensional array is also called one-dimensional array.

 

DataType[] VariableName = new DataType[Number];

 

In the above declaration DataType can be char, int, float, double, decimal, string, etc.

 

VariableName is the name of the array.

 

The square brackets [] on the left of the assignment operator are used to let the compiler know that you are declaring an array instead of a normal variable.

 

The new operator allows the compiler to reserve memory.

 

The [Number] factor is used to specify the number of items of the list.

 

Declaring single dimensional array

 

int[] arr = new int[10];

 

double numbers = new double[5];

 

string[] names = new string[2];

 

Single dimensional array initialization

 

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

 

string[] names = new string[] { "Rocky", "Sam", "Tina", "Yoo", "James", "Samantha" };

 

You can omit the size of the array, like this:

 

int[] numbers = new int[] {1, 2, 3, 4, 5};

string[] names = new string[] {"Reena", "Prety", "Rocky", "David");

 

You can also omit the new operator if you initialize array like this:

 

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

string[] names = {"Reena", "Prety", "Rocky", "David"};

 

Practical demonstration of single dimensional array

 

using System;

 

namespace array_example1

{

    class Program

    {

        static void Main(string[] args)

        {

            int[] arr = new int[10];

 

            for (int x = 0; x < 10; x++)

            {

                Console.WriteLine("Enter array element : {0}", x + 1);

                arr[x] = Int32.Parse(Console.ReadLine());

            }

 

            foreach (int i in arr)

            {

                Console.WriteLine(i);

            }

            Console.ReadLine();

        }

    }

}

 

Note: If you do not initialize an array at the time of declaration, the array members are automatically initialized to the default initial value for the array type. Also, if you declare the array as a field of a type, it will be set to the default value null when you instantiate the type.

 

Something about foreach 

  • In a for loop, you should know the number of element of the array. If you don't, the C# language allows you to let the compiler use its internal mechanism to get this count and use it to know where to stop counting. To assist you with this, C# provides the foreach operator.
  •  foreach loop is used on enumerator type only.
  •  foreach is read-only loop.

Multidimensional arrays (rectangular arrays)

 

Arrays can have more than one dimension; these arrays-of-arrays are called multidimensional arrays. They are very similar to standard arrays with the exception that they have multiple sets of square brackets after the array identifier.

 

The most common kind of multidimensional array is the two-dimensional array. A two dimensional array can be thought of as a grid of rows and columns.

 

Declaring multidimensional array

 

string[,] names = new string[4, 4];

int[,] numbers = new int[3, 4];

 

Multidimensional array initialization

 

int[,] numbers = new int[3, 2] {{1,2}, {3,4}, {5,6}};

string[,] names = new string[2, 2] {{"Ana", "Anita"}, {"Bob", "Barbie"}};

 

You can omit the size of the array, like this:

 

int[,] numbers = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } };

string[,] names = new string[,] {{"Ana", "Anita"}, {"Bob", "Barbie"}};

 

You can also omit the new operator if you initialize array like this:

 

int[,] numbers = {{1,2}, {3,4}, {5,6}};

string[,] names = {{"Ana", "Anita"}, {"Bob", "Barbie"}};

 

Practical demonstration of multidimensional array

 

using System;

 

namespace array_multidim

{

    class Program

    {

        static void Main(string[] args)

        {

 

            //declaring a array with 4 rows and 3 columns

            int[,] arr = new int[4, 3];

 

            //accepting values in the array

            for (int x = 0; x < 4; x++)

            {

                Console.WriteLine("Enter row element : {0}", x + 1);

                for (int y = 0; y < 3; y++)

                {

                    arr[x, y] = Int32.Parse(Console.ReadLine());

                }

            }

 

            // displaying values of multidimensional array

            for (int x = 0; x < 4; x++)

            {

                Console.WriteLine("Values of row : {0}", x + 1);

 

                for (int y = 0; y < 3; y++)

                {

 

                    Console.Write(arr[x, y] + "\t");

                }

                Console.WriteLine();

            }

 

            Console.ReadLine();

        }

    }

}

 

Jagged Arrays (array-of-arrays)

 

Jagged arrays are often called array of arrays. More specifically, a jagged array is an array of vectors. Unlike rectangular arrays, a jagged array, as the name implies, is jagged as each vector in the array can be of different length.

 

It is also possible to have jagged arrays, whereby  "rows" may be different sizes. For this, you need an array in which each element is another array. However, all this is only possible if the arrays have the same base type.

 

Declaring and initializing jagged array.

 

int[][] jaggedArray = new int[2][];

 

jaggedArray[0] = new int[3];

jaggedArray[1] = new int[5];

 

jaggedArray[0] = new int[] { 3, 5, 7, };

jaggedArray[1] = new int[] { 1, 0, 2, 4, 6 };

 

You can also initialize the array upon declaration like this:

 

int[][] jaggedArray = new int[][]

{

new int[] { 3, 5, 7, },

new int[] { 1, 0, 2, 4, 6 }

};

 

You can use the following shorthand form:

int[][] jaggedArray =

{

new int[] { 3, 5, 7, },

new int[] { 1, 0, 2, 4, 6 }

};

 

Note: Notice that you cannot omit the new operator from the elements initialization because there is no default initialization for the elements.

 

A jagged array is an array of arrays, and therefore its elements are reference types and are initialized to null.

 

It is possible to mix jagged and multidimensional arrays. The following is a declaration and initialization of a single-dimensional jagged array that contains two-dimensional array elements of different sizes:

 

int[][,] jaggedArray = new int[4][,]

{

new int[,] { {11,23}, {58,78} },

new int[,] { {50,62}, {45,65}, {85,15} },

new int[,] { {245,365}, {385,135} },

new int[,] { {1,2}, {4,4}, {4,5} }

};

 

Practical demonstration of jagged array

 

using System;

 

namespace array_jagged

{

    class Program

    {

        static void Main(string[] args)

        {

            // Declare the array of four elements:

            int[][] arr = new int[4][];

 

            // Initialize the elements:

            arr[0] = new int[2] { 7, 9 };

            arr[1] = new int[4] { 12, 42, 26, 38 };

            arr[2] = new int[6] { 3, 5, 7, 9, 11, 13 };

            arr[3] = new int[3] { 4, 6, 8 };

 

            // Display the array elements:

            for (int i = 0; i < arr.Length; i++)

            {

                System.Console.Write("Element({0}): ", i + 1);

 

                for (int j = 0; j < arr[i].Length; j++)

                {

                    System.Console.Write("{0}{1}", arr[i][j], j == (arr[i].Length - 1) ? "" : " ");

                }

                System.Console.WriteLine();

            }

            Console.ReadLine();

        }

    }

}

 

Mixed Arrays

 

Mixed arrays are a combination of multi-dimension arrays and jagged arrays. Multi-dimension arrays are also called as rectangular arrays.

 

Understanding the Array Class

 

Arrays are extremely useful when you have several similar objects that you want to be able to process the same way or to be able to process as a group rather than individually.

 

The Array class, defined in the System namespace, is the base class for arrays in C#. Array class is an abstract base class, which can't be inherited, but it provides CreateInstance method to construct an array.

 

System.Array class provides methods for creating, manipulating, searching, and sorting arrays, thereby serving as the base class for all arrays in the common language runtime.

 

Array class properties

 

IsFixedSize

Return a value indicating if an array has a fixed size or not.

Length

Returns the total number of items in all the dimensions of an array

Rank

Returns the number of dimensions of an array.

SyncRoot

Returns an object that can be used to synchronize access to the array.

 

Array class methods

 

BinarySearch

This method searches a one-dimensional sorted Array for a value, using a binary search algorithm.

Clear

This method removes all items of an array and sets a range of items in the array to 0.

Clone

This method creates a shallow copy of the Array.

Copy

This method copies a section of one Array to another Array and performs type casting and boxing as required.

CopyTo

This method copies all the elements of the current one-dimensional Array to the specified one-dimensional Array starting at the specified destination Array index.

CreateInstance

This method initializes a new instance of the Array class.

GetEnumerator

This method returns an IEnumerator for the Array.

GetLength

This method returns the number of items in an Array.

GetLowerBound

This method returns the lower bound of an Array.

GetUpperBound

This method returns the upper bound of an Array.

GetValue

This method returns the value of the specified item in an Array.

IndexOf

This method returns the index of the first occurrence of a value in a one-dimensional Array or in a portion of the Array.

Initialize

This method initializes every item of the value-type Array by calling the default constructor of the value type.

LastIndexOf

This method returns the index of the last occurrence of a value in a one-dimensional Array or in a portion of the Array.

Reverse

This method reverses the order of the items in a one-dimensional Array or in a portion of the Array.

SetValue

This method sets the specified items in the current Array to the specified value.

Sort

This method sorts the items in one-dimensional Array objects.

 

Conclusion

 

Well, I hope that you've benefited, at least a little, from this array tutorial. Your feedback and constructive contributions are welcome.  Please feel free to contact me for feedback or comments you may have about this article.

Up Next
    Ebook Download
    View all
    Learn
    View all