C# Array Class

shabbir's Avatar author of C# Array Class
This is an article on C# Array Class in C#.
The array is one of those data structures which have been in use since the advent of the programming languages. Be it C, C++, Java, PHP or any other web-based, desktop or mobile application development, you will find an array data structure to hold records of data. Syntax may be different but the concept would be same. Keeping in view the importance of array in application, .NET framework provides you an explicit Array class that performs functionalities of a standard array.

The Array class in .NET serves as base class for all the single and multi-dimensional arrays. Of all the collection classes that .NET framework provides, the Array class is the one that implements all standard collection interfaces. Another exciting feature of the Array class is type unification which allows all the arrays to have a common set of methods that can be array irrespective of the type of the array.

As aforementioned, all the collection interfaces are implemented by the Array class, up to IList<T> interface. While implementing IList<T> interface, the Array class makes slight modification. The Add() and Remove() methods which are usually public in the classes that implement IList<T>interface, are not public in Array class because on fixed-length collections such as arrays, these methods throw exception. But Array class has a Resize method. You must be wondering that if array are fixed size collection then how it can be resized. The answer is that when you call static resize method on an array, what actually happens is that internally a new array of the specified size is created and all the elements in old array are copied into the new one. However, it is recommended that you should use IList collection if you want a resizable collection.

An interesting thing to note here is that, an Array class can store both reference as well as value types. Value types are stored directly in an array and occupy contagious memory locations, where as reference types are not stored directly in the memory; instead they are stored in non-contagious memory locations and their references are stored contagiously in an array. For instance, you have 4 long integers and you want to store them in an array. They would take 32 bytes of contagious memory locations. (One long integer contains 8 bytes). However, in case of reference variables, the reference of value types will be stored in memory which will be 4 bytes in case of a 32 bit system and 8 bytes in case of a 64 bit system.

Jump to:Arrays class can hold both value types and reference type data but Array class itself is a reference type variable. This means that if you array1 = array2, both of these arrays would point to a single reference. But if you have two arrays that contain same elements but different references, comparing them using Equals method would return false. To compare such Array classes, you can us StructuralComparisons types which were introduced in .NET framework 4.0. Our first example explains this concept.

Example1
Code:
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Numerics;

namespace CSharpTutorial
{
    class Program
    {
        public static void Main()
        {
            object[] arr1 = new object[] { "James", 24, true };
            object[] arr2 = new object[] { "James", 24, true };

            if (arr1 == arr2)
            {
                Console.WriteLine("Arrays are equal");
            }
            else
            {
                Console.WriteLine("Arrays are not equal");
            }

            Console.WriteLine("\nUsing Strucutral comparison ...\n");
            IStructuralEquatable compare = arr1;

            if (compare.Equals(arr1, StructuralComparisons.StructuralEqualityComparer))
            {
                Console.WriteLine("The arrays are equal and have same items.");
            }
            else
            {
              Console.WriteLine("The arrays are not equal.");
            }
            Console.ReadLine();
        }
    }
}
Consider the code in Example1. Here we have declared two arrays of type ‘object’. We have named them arr1 and arr2. In both of these arrays we have stored three items: A string named “James”, and integer 24 and a bool which we have initialized to true. Both arrays have exactly same items. In the next lines we are comparing these arrays using simple comparison operator “==”. This would evaluate to false; the reason be that these two arrays would be pointing to different memory locations. We said earlier that Array class can store both reference and value type data but itself Array class is a reference type. Therefore, if you compare two arrays using ordinary comparison operator “==” the comparison would be made between their memory address and since arr1 and arr2 are referring to different memory locations therefore the result of the comparison would be false although arrays have same elements. So how to find out if two array contain similar elements or not?

.NET framework provides special types for these purposes, which are called StrucuturalComparison types. These types allow developer to compare if array contains similar elements or not. Before using StructuralComparison types, we have to first create an object if IStructuralEquatable interface. This interface has an Equals method to which we pass StructuralComparison type. We did this in the following line of code
Code:
compare.Equals(arr1, StructuralComparisons.StructuralEqualityComparer)
Now when you use StructuralComparison types for comparing two arrays, if the arrays contain similar elements, comparison would evaluate to true. So in the output, we would see that comparing arr1 and arr2 using simple comparison operator would yield to false and when these two arrays are compared using StructuralComparison types, the comparison would evaluate to true. The output of the code in Example1 is as follows.

Output1



Array Construction and Indexing



In C#, there are two ways to construct arrays. You can use C# language construct to create arrays. This is more traditional way of construction arrays. Consider Example2 to see how arrays can be created in C# in traditional ways.

Example2
Code:
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Numerics;

namespace CSharpTutorial
{
    class Program
    {
        public static void Main()
        {
            int[] numbers = new int[10];

            numbers[0] = 10;
            numbers[1] = 20;
            numbers[2] = 30;
            numbers[3] = 40;
            numbers[4] = 50;

            foreach (int num in numbers)
            {
                Console.WriteLine(num);
            }
            Console.ReadLine();
        }
    }
}
Here we have created array using traditional method.
Code:
int[] numbers = new int[10];
The above line of code means that we want to create an array of type integer whose name is numbers. On the right side of equals sign we created a new array instance using ‘new’ keyword because we have mentioned earlier that in C#, an Array class is actually a reference type, therefore we have to use new keyword in order to create the object of this type. We have specified that this array can hold 10 elements of type integer.

In the next line of code we have accessed the index of the array using the following line of code
Code:
numbers[0] = 10;
The above line of code means that at 0th index of numbers array, store element 10. Note, array index always start from 0, which means that 0th index actually contain first element of the array. We have stored some numbers at the 1st to 4th indexes as well. So now, we have 5 indexes where some integers have been stored and 5 indexes are empty.

Now come to some more interesting facts, you can see that we have used foreach loop to traverse the elements of the array. It is due to the fact that Array class implements IEnumerable interface and any class that implements IEnumerable interface can be traversed using foreach loop. Therefore, we used foreach loop to display the elements of the array. The output of the code in Example2 is as follows.

Output2



Now a question should come to your mind that in the output, first five elements are the elements that we stored in the array, but why the last five elements are zero although we didn’t store zero in the last five indexes of the numbers array. The answer to this question is simple. In integer type array, if you do not store any element at array indexes, by default zero is stored in that index when program is compiled. You can also dynamically store elements in array during declaration as we did in Example1 where we stored elements dynamically in arr1 and arr2 using following lines of code.
Code:
object[] arr1 = new object[] { "James", 24, true };
object[] arr2 = new object[] { "James", 24, true };
This is the first method of constructing and indexing arrays in C#. Now come to a more interested method of creating arrays in C#.

You can create an array in C# by calling Array.CreateInstance method where you can dynamically specify the type of the array along with the dimensions of the array. C# contains GetValue and SetValue static methods which can be used to get and set values at particular index of the array. In our next example, we are going to explain that how arrays can be created using Array.CreateInstance and how index can be accessed using GetValue and SetValue methods. Have a look at Example3.

Example3
Code:
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Numerics;

namespace CSharpTutorial
{
    class Program
    {
        public static void Main()
        {
            Array numbers = Array.CreateInstance(typeof(int), 10);

            numbers.SetValue(10, 0); // numbers[0] = 10;
            numbers.SetValue(20, 1); // numbers[1] = 20;
            numbers.SetValue(30, 2); // numbers[2] = 30;
            numbers.SetValue(40, 3); // numbers[3] = 40;
            numbers.SetValue(50, 4); // numbers[4] = 50;

            foreach (int num in numbers)
            {
                Console.WriteLine(num);
            }

            int num1;
            num1 = (int)numbers.GetValue(0);
            Console.WriteLine("\nAccessing value using GetValue: "+ num1);
            Console.WriteLine("\nCasting to tradtional array ...\n");

            int[] numbers2 = (int[])numbers;
            foreach (int num in numbers2)
            {
                Console.WriteLine(num);
            }
            Console.ReadLine();
        }
    }
}
Pay attention to the above code. Here we have created an array numbers using Array.CreateInstance method. To this method we passed type and the length of array which is int and 10 respectively. This method will return an integer type array with length 10. This array will be stored in the variable numbers of type Array.

In the next lines of code, we have called SetValue static method on numbers array and have stored values in it. SetValue method takes two parameters, first one is the object you want to store and the second parameter is the index at which you want to store your object. So the line ‘numbers.SetValue(30, 2)’ means that in array numbers store value 30 at index 2 which is actually the third index since array indexes start from 0. We have stored five values by calling this SetValue method and have then printed them using foreach loop.

Next, we have explained how you can use GetValue method to access particular element in this following line.
Code:
num1 = (int)numbers.GetValue(0);
The above line of code means that get element at 0th index of numbers array and cast it to integer type. Then store this value in integer variable num1. We have to cast value at array index into corresponding type because constructing arrays using this method treats every element as an object.

We can also cast arrays created using Array.CreateInstance method to traditional arrays. We have done this in Example3 in following lines.
Code:
int[] numbers2 = (int[])numbers;
Here we are creating another array ‘numbers2’ and storing in it numbers array after parsing it into integer type array. We have displayed the element of this array as well. We would see that both arrays i.e. numbers and numbers2 would contain same elements. The output of the code in Example3 is as follows.

Output3



Searching in Array Class



Array class offers wide variety of methods for searching elements within an array. Following are some of the searching methods.
  • BinarySearch methods - These methods use traditional binary search algorithm to search elements within a sorted array.
  • IndexOf & LastIndex methods - These methods are used to search elements on the basis of index. Array doesn’t need to be sorted for these methods.
  • Find, FindLast, FindAll, FindIndex, FindLastIndex, TrueForAll & Exists - These elements perform searching on the basis of some Predicate<T>. These methods are applicable on unsorted arrays.
A demonstration of usage of Find() and FindAll() methods have been given in our next example. Have a look at Example4 for further understanding.

Example4
Code:
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Numerics;

namespace CSharpTutorial
{
    class Program
    {
        public static void Main()
        {
            string[] cars = { "Toyota", "Honda", "Suzuki", "BMW", "Santra" };
            Console.WriteLine(Array.Find(cars, c => c.Contains("u")));
            string [] strcar = Array.FindAll(cars, c => c.EndsWith("a"));

            foreach (string name in strcar)
            {
               Console.WriteLine(name);
            }
            Console.ReadLine();
        }
    }
}
In our Example4, we have an array of strings which we have named “cars”. This array contains 5 elements that are basically names of the cars. In the next line of code we have first used ‘Find’ method. This method takes two parameters: first one is the array on which you want to perform particular operation and the second parameter is the predicate on the basis of which you want to perform searching in the array. Though we can use ordinary predicates to perform searching within arrays but it is always better to use lambda expression for this purpose. Lambda expressions are much more readable and easier to understand and in fact write as well if you have got strong understanding of lambda expressions. In the second parameter of the Find method we have written a lambda expression i.e. cars, c => c.Contains("u"). This lambda expression means that in the array that has been passed to Find method as the first parameter, find those strings that contain string “u”. Since in our car array, we have only one string which contains “u”, therefore the return element would be the string “Suzuki”. This string has been displayed on the output screen.

Next, we have explained the usage of FindAll method. This method also takes two parameters: first is the array in which searching has to be performed and the second parameter is the predicate which is lambda expression in our case. Difference between a simple Find method and FindAll method is that the former returns single element whereas the latter returns array of elements that satisfy the predicate. In our Example, we have written a lambda expression which finds all the string elements that ends with string ‘a’. As in our cars array we have three strings that end with ‘a’ therefore FindAll method would return a string array that would contain elements ‘Toyota’, ‘Honda’ and ‘Santra’. The output of the code in Example4 is as follows.

Output4



It can be seen that the first element is ‘Suzuki’ which would be returned by Find method where we have a predicate which finds elements that end with ‘i’. Similarly, the next three strings are the ones which end with ‘a’ as specified in FindAll method.

Sorting Array Class



The next important task that we often need to perform is sorting the elements in an array. Fortunately enough, .NET framework provides built-in array sorting mechanism. In our next example we are going to explain with the help of example that how you can sort a C# array by calling sort method. Have a look at our 5th example of this article.

Example5
Code:
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Numerics;

namespace CSharpTutorial
{
    class Program
    {
        public static void Main()
        {
            int[] numbers = { 4, 6, 3, 1, 2, 5 };

            Console.WriteLine("Array before sorting");
            foreach (int num in numbers)
            {
                Console.Write(num + ", ");
            }

            Array.Sort(numbers);

            Console.WriteLine("\n\nArray after sorting");
            foreach (int num in numbers)
            {
                Console.Write(num + ", ");
            }

            int [] numbers2 = { 4, 6, 3, 1, 2, 5 };
            string[] words = { "Four", "Six", "Three", "One", "Two", "Five" };

            Array.Sort(numbers2, words);

            Console.WriteLine();
            foreach (string str in words)
            {
                Console.Write(str + ", ");
            }
            Console.ReadLine();
        }
    }
}
Have a look at the code in Example5. Here we have an integer array which we have named numbers. This array contains integer values from 1 to 6 but these integers are arranged in some random order and the array is unsorted. First we have displayed this unsorted array on the screen.

Next line of code is important, here we have called ‘Sort’ static method of array class and have passed it out unsorted array. This method would internally sort the elements of the array. We have again displayed the elements of the numbers array and this time you would see that elements have been displayed in the sorted order.

Now come towards an even interesting aspect of Sort method. We again declared an integer type array and named it numbers2 and again stored first 6 integers in it in random order. We then declared a string type array and have stored six elements in it. These elements are basically numbers from 1 to 6 in words. We then called Sort method of the Array class and then passed both numbers2 and words arrays as parameter. Now, what happens is that actually Sort method, before sorting would map the first element of the first array to the first element of the second array. Therefore, integer 4 of the numbers2 array would be mapped to “Four” string of the words array. Simply putting, first element of the first array maps to first element of the second array. Second element of the first array maps to second element of the second array and so on and so forth. It doesn’t matter that there has to be string “Four” at the first index of the words array. Anything at the first index of words array would be mapped to first index of the numbers2 arrays. Now, when sorting is done, it would be done on the basis of the first arrays, which means that when Sort method places integer ‘1’ on the first index of the numbers2 array, it would look that which element in the second array was mapped to the integer 1 in the first array. It would find that string “One” was mapped to integer 1. Therefore, in the words array, it would store “One” on first index. And this way, all the elements in both arrays would be sorted.

Array class is an extremely important type in C# programming and is probably the most widely used collection for storing elements. In this article, we have briefly explored some of the most fascinating and useful features of Array class. I would recommend you to further explore this class own your own and implement the remaining array methods that have not been explained in this article.