Convert ArrayList to Array

In this article I will explain how to Convert ArrayList to Array.
  • 2231

Introduction

In this article I will discuss the conversion from arraylist to array by using ToArray method. An ArrayList has similarities to an array. It stores a one-dimensional collection of elements. It can be converted to an array with the ToArray method. ToArray is found on the ArrayList type.

Example

namespace ConsoleApplication2

{

    class Program

    {

        static void Main(string[] args)

        {

            //create the arraylist

            ArrayList arraylist1 = new ArrayList();

            arraylist1.Add("June");

            arraylist1.Add("July");

            arraylist1.Add("August");

            arraylist1.Add("September");

            arraylist1.Add("October");

            Console.WriteLine("THE ELEMENTS OF THE ARRAYLIST ARE:");

            Console.WriteLine();

            foreach (string i in arraylist1)

            {

                Console.WriteLine(i);

            }

            //create an array

            string[] array = arraylist1.ToArray(typeof(string)) as string[];

            Console.WriteLine();

            Console.WriteLine("Arraylist elements are copied to array");

            Console.WriteLine("THE ELEMENTS OF THE ARRAY ARE:");

            Console.WriteLine();

            foreach (string value in array)

            {

                Console.WriteLine(value);

            }       

        }

    }

}

 

Output

 conversion.jpg

Ask Your Question

Got a programming related question? You may want to post your question here
 

 

Categories

More Articles

© 2019 DotNetHeaven. All rights reserved.