Obtains an array containing all the elements of the collection. - CSharp System

CSharp examples for System:Array Convert

Description

Obtains an array containing all the elements of the collection.

Demo Code


using System.IO;/*w w  w .  j  a v a  2s . c  om*/
using System;

public class Main{
        /// <summary>
        /// Obtains an array containing all the elements of the collection.
        /// </summary>
        /// <param name="objects">The array into which the elements of the collection will be stored.</param>
        /// <returns>The array containing all the elements of the collection.</returns>
        public static Object[] ToArray(System.Collections.ICollection c, Object[] objects)
        {
            int index = 0;

            Type type = objects.GetType().GetElementType();
            Object[] objs = (Object[])Array.CreateInstance(type, c.Count);

            System.Collections.IEnumerator e = c.GetEnumerator();

            while (e.MoveNext())
                objs[index++] = e.Current;

            //If objects is smaller than c then do not return the new array in the parameter
            if (objects.Length >= c.Count)
                objs.CopyTo(objects, 0);

            return objs;
        }
        /// <summary>
        /// Returns an array containing all the elements of the collection.
        /// </summary>
        /// <returns>The array containing all the elements of the collection.</returns>
        public static Object[] ToArray(System.Collections.ICollection c)
        {
            int index = 0;
            Object[] objects = new Object[c.Count];
            System.Collections.IEnumerator e = c.GetEnumerator();

            while (e.MoveNext())
                objects[index++] = e.Current;

            return objects;
        }
}

Related Tutorials