How to get an Array from an Arraylist in C#

 
Sometimes we need to get an array from arraylist, Suppose if you need to pass an array to a method that is not overloaded to accept a collection etc. then you need to converting an array from arraylist like this there are many situation when you are working with arraylist.We can do this by calling ToArray().
following program show that how to convert arraylist into array.

private void SortAndSearchArrayList()
        {
            ArrayList ArrList = new ArrayList();
            ArrList.Add(21);
            ArrList.Add(30);
            ArrList.Add(25);
            ArrList.Add(22);
            ArrList.Add(20);
            ArrList.Add(35);
            ArrList.Add(24);
 
            string OriginalStr = "";
            foreach (int i in ArrList)
            {
                OriginalStr = OriginalStr + i + " ";
            }
            //value of originalStr=21 30 25 22 20 35 24
 
            //Converting into an array
            int[] Arr = (int[])ArrList.ToArray(typeof(int));
            int Sum = 0;
            for (int i = 0; i < Arr.Length; i++)
            {
                Sum = Sum + Arr[i];
            }