.Net framework ArrayList.CopyTo(Array) method allow us to copy the entire ArrayList to a compatible one-dimensional Array, starting at the beginning of the target array. this arraylist CopyTo() method exists under System.Collections namespace.
this method require to pass a parameter named ‘array’. the ‘array’ parameter value type is System.Array which represents the one-dimensional Array that is the destination of the elements copied from ArrayList. the Array must have zero-based indexing.
the CopyTo() method has three exceptions. this method throw ArgumentNullException exception, if the ‘array’ is null. CopyTo() method throw ArgumentException exception, if the ‘array’ is multi-dimensional or the number of elements in the source arraylist is greater than the number of elements that the destination ‘array’ can contain. arraylist CopyTo() method throw InvalidCastException exception, if the type of the source arraylist cannot be cast automatically to the type of the destination array.
the following console c# example code demonstrate us how can we copy an arraylist to a compatible one dimensional array programmatically at run time in an console application.
C# Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | class Program { static void Main(string[] args) { ArrayList colors = new ArrayList() { "Orange", "Tomato", "Salmon" }; Console.WriteLine("ArrayList Elements...."); foreach (string color in colors) { Console.WriteLine(color); } string[] favoriteColors = { "Green", "SpringGreen", "MediumGreen", "SeaGreen", "LawnGreen" }; Console.WriteLine("\nArray Elements..."); foreach (string color in favoriteColors) { Console.WriteLine(color); } colors.CopyTo(favoriteColors); Console.WriteLine("\nAfter Call CopyTo() Method; Array Elements..."); foreach (string color in favoriteColors) { Console.WriteLine(color); } Console.ReadLine(); } } |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | Salmon Array Elements... Green SpringGreen MediumGreen SeaGreen LawnGreen After Call CopyTo() Method; Array Elements... Orange Tomato Salmon SeaGreen LawnGreen |