TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to C-SHARP

C# Convert ArrayList to Array (Use ToArray)

Convert an ArrayList to an array with typeof and the ToArray method.
Convert ArrayList, array. 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.ArrayListConvert
Example. You will need to provide a Type parameter to the ToArray method on ArrayList. This is because otherwise the method would not know what type to convert each element to. Here we do that with the typeof operator.TypeTypeof, nameof

Note: The string keyword is used, and not a string literal. Specifying types with "String Names" is less clear.

Main: The code populates a new ArrayList with 4 object instances containing string data (string literals).

Cast: The as-cast is necessary to use strong typing on the result from ToArray. It will result in a null value if the cast does not succeed.

AsNull
C# program that converts an ArrayList using System; using System.Collections; class Program { static void Main() { // // Create an ArrayList with 4 strings. // ArrayList list = new ArrayList(); list.Add("flora"); list.Add("fauna"); list.Add("mineral"); list.Add("plant"); // // Convert ArrayList to array. // string[] array = list.ToArray(typeof(string)) as string[]; // // Loop over array. // foreach (string value in array) { Console.WriteLine(value); } } } Output flora fauna mineral plant
Internals. When we open up the ToArray instance method in IL Disassembler, we see that this method (along with the CopyTo method) calls into the Array.Copy method. Array.Copy uses an external, native-code implementation.Array.Copy

Tip: This provides superior performance over manually copying elements in your C# program.

Summary. We used the ArrayList's ToArray method to convert the contents of an ArrayList to a string array. The example here can be adapted to other reference and value types. We also looked inside the base class library.Convert ArrayList to List
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf