TheDeveloperBlog.com

Home | Contact Us

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

<< Back to VBNET

VB.NET Convert ArrayList to Array

Convert an ArrayList to an array. Invoke the ToArray Function.
Convert ArrayList, Array. An ArrayList can be converted to an array. This is possible with the ToArray Function. With it we get an Object array from an ArrayList. ToArray is useful—it is not the same as the ToArray extension from System.Linq.
To start, we create an ArrayList and populate it with three String references. Please notice how all the elements in the ArrayList are of type String. This is important—when we call ToArray, we get an Object array, not a String array.

However: When we loop through the Object array, we can cast each element to a String.

Object Array

Note: We can not directly cast the array to a String(). This exception is reported.

Quote: Unhandled Exception: System.InvalidCastException: Unable to cast object of type 'System.Object[]' to type 'System.String[]'.

VB.NET program that converts ArrayList to Object array Module Module1 Sub Main() ' Create ArrayList. Dim list As ArrayList = New ArrayList() list.Add("Dot") list.Add("Net") list.Add("Perls") ' Get array of objects. Dim array() As Object = list.ToArray() For Each element In array ' Cast object to string. Dim value As String = element Console.WriteLine(value) Next End Sub End Module Output Dot Net Perls
Discussion. The ArrayList makes converting your collection to an array more difficult. If you use the List type, you can convert to a typed array such as String(). This results in much clearer code. I recommend the List type in almost all programs.List
Summary. We used the ToArray function on the ArrayList type to convert an ArrayList to an Object() array. We looked at the exception that is thrown when you try to cast the result array, and also pointed out the superior List type.ArrayListArray
© 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