Question

I am trying to populate a dictionary with 4 keys, each key value is a multi-dimensional array (13,7). The first key and array populate perfectly. When the second key populates, the values for both the first and second keys have the second array iterations values and this continues for the next 2iterations until I have 4 keys and all the same values. I have validated line by line using a watch to verify each array has unique values and each key has a unique value. Any help would be greatly appreciated.

 Dim BitMap As New Dictionary(Of String, String(,))
 For y = 0 To strDiffEQName.Length - 1
        For x = 0 To 1
            Dim intFirst As Integer = Array.IndexOf(rowvalue, "[" & strSTKName & "_" & strSendRecv(x) & "_" & strDiffEQName(y) & "]") 'Find first string in Array (Start Block)
            Dim intSecond As Integer = Array.LastIndexOf(rowvalue, "[" & strSTKName & "_" & strSendRecv(x) & "_" & strDiffEQName(y) & "]") 'Find second string in Array (Stop Block)
            Dim intNum As Integer = 0

            For i As Integer = intFirst + 1 To intSecond - 1 'Loop through array betwween start and stop block
                Dim strHolder() As String 'Array that will temporary hold values until transfered to the strString Array
                strHolder = rowvalue(i).Split(","c) 'load data between commas to the temporary array
                ReDim Preserve strHolder(strHolder.Length - 1) 'Increase rows in array by one
                For k As Integer = 0 To 7
                    strString(intNum, k) = strHolder(k) 'Load temp data into multi-dimensional array
                Next
                intNum = intNum + 1 'Increment to next row in Multi-dimensional array
            Next
            BitMap.Add(strSendRecv(x) & "_" & strDiffEQName(y), strString) 'Transfer Multi-dimensional array to Dictionary
        Next
    Next
Was it helpful?

Solution

As has been said, arrays are reference types. That can't be changed. If you want to add four items to the Dictionary then you have to create four arrays. It's that simple. If you just create one array and add that four times then obviously you'll only see one set of data regardless of the item in the Dictionary you look at.

Consider this. Let's say that you are taking a list of people's names and the colour of the shirt they are wearing. I step up wearing a red shirt and you take down my details. I then step up again wearing a blue shirt and you take done my details again. If you then call my name from the first item, would you expect me to be magically wearing a red shirt again, even though I took it off and put on a blue shirt? I'm only one person, no matter how many times you put my name on the list, so you're going to see the last colour shirt I put on, no matter what list item you use to select me. That's how objects work in the real world and that's how objects work in programming.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top