For my code I need to change a arrayList to a string array.

I did it like this

ArrayList tempList = new ArrayList();
//some code to put strings into the list
stringArray = (string[])tempList.ToArray(typeof(string));

It's the last line I don't get. In the ToArray method you set the type as a string[], so why do you still need the cast?

Recommended Answers

All 4 Replies

ToArray() attempts to cast all the objects into the type specified (the typeof part). It then returns a generic Array type. If you don't want to use the Array type, you have to cast it into the type you want (the string[] part).


string[] result = ( string[] )myArray.ToArray( typeof( System.String ) );

I see, thank you =)

string[] strArray = arrList.ToArray(typeof(string)) as string[];

pls try this code for change array list to string liost

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.