Reputation: 67
I have 2 arraylists in my project, list1, and list2. (both contains 9 String values, car1, car2, car3 and so on.
I also have an string array, called store_numbers which can contain 52 String elements. Now I wanna copy my values from list1 and list2 to the array. By doing :
list1.CopyTo(store_numbers,0);
Which I think is the right way I get the error message
At least one element in the source could not be cast down to the destination array type
Anyone who knows how I can Fix this?
Thanks!
Upvotes: 0
Views: 5488
Reputation: 46641
You probably have something close to this:
ArrayList list1 = new ArrayList{"car1",2,"car3","car4","car5",
"car6","car7","car8","car9"};
string[] store_numbers = new string[] {"10","11","12","13","14","15",
"16","17","18"};
list1.CopyTo(store_numbers,0);
The above will throw the following error:
`At least one element in the source array could not be cast
down to the destination array type.`
There is the number 2 in list1, that is why you get the error in this case. Change to List<string>
to avoid this.
Upvotes: 1
Reputation: 3883
make sure all items in your ArrayList
have the same datatype.if not, you have to convert all items to string before copying it.
Upvotes: 0
Reputation: 69270
Are you really sure that the arraylists only contain strings? The error message indicates that at least one object in one of the arraylists isn't a string. If you set a breakpoint at the place where the problem occurs you should be able to look at the arraylist contents.
Also you shouldn't be using ArrayList
at all - it is deprecated. Use List<String>
to get type safety.
Upvotes: 1
Reputation: 97778
You have something in your ArrayList
that isn't a string.
The best fix is not to use ArrayList
! It's been obsolete since .NET 2.0 came out. Use a List<string>
instead. Then the compiler will prevent you from putting a non-string in the list in the first place, and your copy should work fine.
Upvotes: 12