Signup/Sign In

C# Array Class

Posted in Programming   LAST UPDATED: OCTOBER 10, 2019

    In our previous article, we discussed the arrays and their types. So, continuing on from the previous article examples, we will discuss the Array class and its most common methods and properties in this tutorial.

    Note: In this tutorial, you may come across some terms which you might be unaware of like Exception, Namespace, Collection, Interface, etc. Please, don't worry, we will be covering those topics in the upcoming articles for C# programming language.




    What is the Array class?

    In C# programming, Array class is considered as a collection because it based on the IList interface. The Array class is serving as the base class of all the arrays; it provides predefined methods to perform the operations on array elements like creating an array, searching data in array, sorting array data, etc. and it is the part of System namespace.

    The following table shows the most commonly used properties with a short description:

    Properties Description
    IsFixedSize It returns a Boolean value and checks whether the given array is of fixed size or not
    IsReadOnly It returns a Boolean value and checks whether the array is ReadOnly or not
    Length It returns the length of an array (integer value) or the number of elements in the array.
    Rank It returns the number of dimensions of the Array (integer value)

    The following table shows the most commonly used methods with a short description:

    Methods Description
    Clear It is used to set a specific range of elements in an array to their default values (as per the data type)
    Copy It used to copy array elements to another array
    GetLength It returns the number of elements in the specified array
    GetLowerBound It returns the lower bound of the array
    GetUpperBound It returns the upper bound of the array
    GetValue It returns the value of a specified position in the single-dimensional array
    IndexOf It returns the index of the first occurrence of a specified object
    Reverse It is used to reverses the sequence of elements in the array
    Sort It is used to sort an array
    ToString It returns a string which represents the current object

    Let's take a practical example of properties and methods.

    Filename: Program.cs (example on Array properties)

    using System;
    namespace Studytonight
    {
        class Program
        {
            public static void Main(string[] args)
            {
                int[] arr = { 10, 11, 100, 101, 110 };
                Console.WriteLine("Is the Array of Fixed Size: " + arr.IsFixedSize);
                Console.WriteLine("Is the Array Read-Only: " + arr.IsReadOnly);
                Console.WriteLine("Length of the Array: " + arr.Length);
                Console.WriteLine("Rank of the Array: " + arr.Rank);
                Console.ReadKey();
            }
        }
    }

    Output:

    Is the Array of Fixed Size: True
    Is the Array Read-Only: False
    Length of the Array: 5
    The rank of the Array: 1

    In the above example, firstly, we used the IsFixedSize property which returned True. If an array is of fixed size, then it won't allow us to add or remove elements, but we can modify the existing elements.

    The IsFixedSize property is always true for all arrays. You might wonder, then why have this property at all? Answer to this question is, Array class implements this property because it required by the System.Collections.IList interface.

    Next, we have used IsReadOnly property and the default value is False (this property is always false for all arrays). It returns True if the Array is read-only; otherwise, false. Arrays are made read-only to prevent any modifications to the array.

    Also, we have used Length and Rank property which is used to return the length of the array and the number of dimensions of the array respectively.

    Following program illustrates the use of some Array methods.

    Filename: Program.cs (example of Array methods)

    using System;
    namespace Studytonight
    {
        class Program
        {
            static void Print(string s, int[] arr)
            {
                Console.Write(s);
                foreach (int i in arr)
                {
                    Console.Write("{0} ", i);
                }
            }
            public static void Main(string[] args)
            {
                int[] arr = { 110, 101, 100, 11, 10, };
                int[] cpyarr = new int[5];
    
                Array.Sort(arr);
                Print("Sorted Array: ", arr);
    
                Array.Copy(arr, cpyarr, arr.Length);
                Print("\nCopied Array: ", cpyarr);
    
                Array.Reverse(arr);
                Print("\nReverse Array: ", arr);
    
                Array.Clear(arr, 0, 3);
                Print("\nClear Array: ", arr);
                Console.ReadKey();
            }
        }
    }

    Output:

    Sorted Array: 10 11 100 101 110
    Copied Array: 10 11 100 101 110
    Reverse Array: 110 101 100 11 10
    Clear Array: 0 0 0 11 10

    In the above example, we have created a method Print which takes two parameters, one is a string, and another is an int type. This method not only helps us to print the array on the console by taking the parameters but has also made the code more logical (less redundant/avoiding unnecessary lines of code) and readable.

    1. The Sort method is used to arrange the elements in ascending order. We have defined the array in an unsorted way and after using Array.Sort(arr) method, all the elements are sorted and printed using the user-defined Print function.

    2. The Copy method is used to copy the array elements into another array. In the program, we have created a new array of size five elements to get the elements copied from the first array arr. We know, the length of our array is 5, and the copy method requires a parameter value length of an array; to copy into another array. Hence, instead of providing the array length manually, we used Length property. The Copy(arr, cpyarr, arr.Length) method will copy the elements from arr to cpyarr by taking the third parameter value as the length of our first array.

    3. The Reverse method is used to reverse the sequence of a specified array. Before using the Reverse method, our array is sorted but after applying this method, all the elements of array gets reversed.

    4. The Clear method is used to clear the array and set the default value for each element. This method requires three parameters, the first parameter is the array itself, the second parameter is the starting position from where you want to clear the values and the third parameter is the ending position(index) upto which you want to clear the values. We passed values to this method as Clear(arr, 0, 3), where arr is the original array, 0 is the starting position, and 3 is the ending position. Therefore, from index 0 to 3 values will be set to the default value as 0 as the array type is int and the remaining elements will remain as it is.

    Let's take one more example which illustrates the use of some other Array methods:

    Filename: Program.cs (example of Array methods)

    using System;
    namespace Studytonight
    {
        class Program
        {
            public static void Main(string[] args)
            {
                int[] arr = { 10, 11, 100, 101, 110 };
    
                Console.WriteLine("Index of an element 110 is {0}", Array.IndexOf(arr, 110));
                //IndexOf method returns the index of an element starting from 0
    
                Console.WriteLine("Length of the Array is {0}", arr.GetLength(0));
                //GetLength method return the lenght of an array by providing dimension (like zero-dimension)
    
                Console.WriteLine("The value at 4 index is {0}", arr.GetValue(4));
                //GetValue method returns an element at specified position starting from 0
    
                Console.WriteLine("The Upper bound of the array is {0}", arr.GetUpperBound(0));
                //UpperBound method returns index of the last element of the specified dimension in the array
    
                Console.WriteLine("The Lower bound of the array is {0}", arr.GetLowerBound(0));
                //LowerBound method returns index of the first element of the specified dimension in the array
    
                Console.ReadKey();
            }
        }
    }

    Output:

    Index of an element 110 is 4
    Length of the Array is 5
    The value at 4 index is 110
    The upper bound of the array is 4
    The lower bound of the array is 0

    We hope this and the previous article helped you to understand the concept of an Array and Array class in C# programming.

    About the author:
    Subject Matter Expert of C# Programming at Studytonight.
    Tags:C#C# TutorialC# Array Class
    IF YOU LIKE IT, THEN SHARE IT
     

    RELATED POSTS