arpit1611 arpit1611 - 20 days ago 5
C# Question

C# Convert ArrayList to List of string?

I have an

ArrayList
, need to add the items of ArrayList into a List of string. I tried the following:

listString.AddRange(new List<string>((string[])this.arrayList.ToArray()))


But this gives an exception of


Unable to cast object of type 'System.Object[]' to type 'System.String[]'


Please note :; I can't use .Cast as I am working in framework
4.0
.

Answer

Use ToArray(typeof(string)) to create an Array and then cast it to a more specific array type string[] before adding it to the variable of type List<string>

listString.AddRange((string[])this.arrayList.ToArray(typeof(string)));