Reputation: 37478
How can I convert from a System::Collections::ArrayList
(containing System::String^
for example) to an array of cli::array<String^>
?
Upvotes: 2
Views: 1464
Reputation: 27864
If the ArrayList is in your code and you can change it, consider changing it to a List<String^>
. You'll get type safety, cleaner code when using the class, more available Linq methods, and the normal builtin method on that class will return an array<String^>
without having to jump through any hoops.
There's a builtin method on ArrayList to do this for you. Call ToArray, and specify the type of the array to be returned.
ArrayList^ list = ...;
array<String^>^ ar = reinterpret_cast<array<String^>^>(list->ToArray(String::typeid));
If you're doing this with other collection types (that aren't using generics), you'll have to do something more manual. You could do it by hand:
ArrayList^ list = ...;
array<String^>^ ar = gcnew array<String^>(list.Count);
for(int i = 0; i < list.Count; i++)
ar[i] = dynamic_cast<String^>(list[i]);
Or you could use Linq to convert the ArrayList to an IEnumerable<String^>
, and then convert that to an array of strings.
ArrayList^ list = ...;
array<String^> ar = Enumerable::ToArray(Enumerable::OfType<String^>(list));
Upvotes: 3