Andreas
Andreas

Reputation: 555

Changing dictionary entrys with a structure as value in Visual Basic 2012

I have this structure:

Public Structure SourceDB
    Public SourceDBid As Integer
    Public SourceDBWimLocationName As String
    Public SourceDBDBName As String
    Public SourceDBIPAdress As String
    Public SourceDBPort As String
    Public SourceDBUsername As String
    Public SourceDBPassword As String
    Public ConnectivityState As String
    Public LastTransmittedId As Integer
End Structure

I am declaring the dictionary in the following way:

Private MySourceDBDictionary As New Dictionary(Of Integer, SourceDB)

Now values get added to the dictionary...

At some point I want to change values of the dictionary in an for each loop:

For Each element As KeyValuePair(Of Integer, SourceDB) In MySourceDBDictionary
    MySourceDBDictionary.Item(element.Key).LastTransmittedId = 0
Next

For some reason this does not work...

The error code is: Expression is a value and therefore cannot be the target of an assignment.

How its it possible, to change already existing values in a dictionary???

Kind Regards! and Thanks.

Upvotes: 1

Views: 4186

Answers (2)

Matt Wilko
Matt Wilko

Reputation: 27322

What you want to do cannot be done with a value type but you can do what you want by reading the Structure out and passing it back.

    For Each element As KeyValuePair(Of Integer, SourceDB) In MySourceDBDictionary
        Dim src = MySourceDBDictionary(element.Key)
        src.LastTransmittedId = 0
        MySourceDBDictionary(element.Key) = src
    Next

This replaces the complete value type with a new 'value'

Alternatively you can use the code you have if you use a Reference Type instead of a Value Type i.e. A Class instead of a Structure. I would suggest that this should be a Class instead of a Structure as you are modifying the values after creation

Upvotes: 2

Swift
Swift

Reputation: 1881

The problem is in the structure take a look at this question Expression Is a value and therefore cannot be the target of an assignment

The above question should be a good explanation to when you should use Structure

Change your struct to a Class and your code should work, also you can change your foreach loop a little to somthing like that:

    For Each element As KeyValuePair(Of Integer, SourceDB) In MySourceDBDictionary
        element.Value.LastTransmittedId = 0
    Next

Upvotes: 2

Related Questions