Question

I'm getting an exception which I don't understand in this bit of code here:

Dim folderList As List(Of String) = _folderList

For Each folder In folderList

    destinationFolder = destinationFolder + "/" + folderName
    localFilePath = lbl_folderPath.Text + "/" + folder

    alterFolderList(localFilePath)

    ...

Next

I've got a global variable _folderList which I copy to another variable, folderList, as seen in the first line of my code. When the last method (alterFolderList) is called, it alters the variable _folderList. When debugging, as I reach the end of the for each for the first time (at Next) I get the exception that the collection was modified, when it actually wasn't because the method called doesn't change it. When debugging, after the method is called, I hover above the variable folderList and I see it changed and is now the same as _folderList but it shouldn't because the variable folderList is equaled to _folderList outside the For Each enumeration.

How does this happen? And how to work around this?

Was it helpful?

Solution

To copy the list you cannot assign it. You should copy the elements. Try this.

Dim folderList As New List(Of String)
folderList.AddRange(_folderList)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top