Dot Net For All

Understanding array in C#

In this article I will discuss about the array in C#, ways in which we can initialize array and various useful commonly used methods of array class which we should know while working with them with code examples and why do we get ‘System.IndexOutOfRangeException’.

Array in C# introduction

Array is a collection of similar datatypes arranged in continuous block of memory. Array in C# is basically 0 index based. It means that first item of the array is stored at 0th location in an array.

Initializing an Array

Following are the ways in which we can initialize an array

            int[] array = new int[2]; // creates array of length 2, default values
            int[] array1 = new int[] { 1, 2 }; // creates populated array of length 2
            int[] array2 = { 1, 2 }; // creates populated array of length 2

In the above code snippet I have initialized array in three ways and all the three ways have created an array of size two. In the first case if we want to assign values to the array element we have to access the array element as shown in below code.

              array[0] = 1;
              array[1] = 2;

The element at first location is assigned using array[0] and similarly at second location using array[1].

Now if we try to add an element to the position 2 to any of the above array we will get an ‘System.IndexOutOfRangeException’ Exception which proves the point that arrays are initialized with the fixed length no matter how we are initializing it.

As the array data is stored in continuous block of memory it is always faster to access array elements.

In the above code snippet we have declared arrays of type int. Similarly we can declare arrays of any type like string, object, byte or may be any custom type.

You can go through this link to have better comparison of Array and Linked List

Array Methods

In this section I will discuss some of the useful methods of array class which we should be aware of.

  1. AsReadOnly– This method returns a read only collection of the type of elements of array as shown in the below code.
                int[] array = { 1, 2, 3 };
                IReadOnlyCollection<int> readOnly = Array.AsReadOnly<int>(array);
  2. Finding Items in Array – We can use the Following methods to find items in an array.
                string[] strArray = {"test", "test1" , "test2" , "test3", "test4"};
    
                int testPos = Array.BinarySearch(strArray, "test");
                int test1Pos = Array.FindIndex(strArray, x => x.StartsWith("test1"));
                bool isTest2There = Array.Exists(strArray, x => x == "test2");
                string lastTest = Array.FindLast(strArray, x => x.StartsWith("test"));

    The fist two methods returns the index of a particular item in the array. Next methods helps us to determine if the item is present in the array and the last methods returns the element which matches a particular condition, in our case we are looking for item which starts with “test”

  3. Iterating an Array – We can use the Array.ForEach method to iterate an array as shown in the below code.
                Array.ForEach(array, x =>
                {
                    Console.Write(x)
                });

    It takes an array as parameter and action for the array elements.

  4. Sorting an Array – If we want to sort an array we can use the Array.Sort method as shown below.
     Array.Sort(array);
  5. Cloning an Array – We can create a clone of the array as shown below
                int[] clonedArray = (int[])array.Clone();
                Console.WriteLine(array[0]); //prints 1
                Console.WriteLine(clonedArray[0]); //prints 1

    Here one thing we need to take are of, as we are creating a clone of array of value types, we get a copy of each value type in the cloned array which means that elements of the both of the arrays do not refer to the same memeory location

    But if we repeat the same cloning process for array of reference type such as string, after a clone is created the array members refer to the same memory location as shown in the following code

                string[] strArray = {"str1", "str2", "str3" };            
                string[] clonedstrArray = (string[])strArray.Clone();
                Console.WriteLine(strArray[0]); //prints str1
                Console.WriteLine(clonedstrArray[0]); //prints str2
    
                bool isReferenceEqual1 = object.ReferenceEquals(strArray[0], clonedstrArray[0]); //returns true
    
                clonedstrArray[0] = "newstring";
    
                Console.WriteLine(strArray[0]); //prints 
                Console.WriteLine(clonedstrArray[0]); //prints 1
    
                bool isReferenceEqual = object.ReferenceEquals(strArray[0], clonedstrArray[0]); //returns false

    As we can see from the above code the first reference comparison returns true but same is not true for the second comparison, as before doing the second comparison we have assigned a new value to the clonedstrArray[0], which assign it to new memory location thus returning false for second reference comparison.

    But if we try the same test for some custom type it will be true for both the scenarios as shown in the below code snippet.

                Person[] personArray = { new Person() { i = 1 } };
    
                Person[] clonedpersonArray = (Person[])personArray.Clone();
                Console.WriteLine(personArray[0].i); //prints  1
                Console.WriteLine(clonedpersonArray[0].i); //prints 1
    
                bool isReferenceEqual1 = object.ReferenceEquals(personArray[0], clonedpersonArray[0]); //returns true
    
                //clonedstrArray[0] = "newstring";
    
                personArray[0].i = 2;
    
                Console.WriteLine(personArray[0].i); //prints 2
                Console.WriteLine(clonedpersonArray[0].i); //prints 2
    
                bool isReferenceEqual = object.ReferenceEquals(personArray[0], clonedpersonArray[0]);  //returns true

    While working with cloning of array we should keep the above point in mind.

  6. Resize an array– AS we know that we have give the size of the array while declaring an array. But if we want to resize an array Resize() method of array comes to the rescue as shown in the following code snippet.
     int[] array1 = new int[] { 1, 2 };
     Array.Resize(ref array, 4);

This article I started with the introduction of arrays and later discussed some of the important functions of the array class which we should always keep in mind while working with them.

Top career enhancing courses you can't miss

My Learning Resource

Excel your system design interview