mardi 17 mars 2015

Property of custom type is unexpectedly nulled when type instance is added to dictionary

When I use my own type in the code below something strange occurs - one of the properties is nulled for all instances in the dictionary AFTER the loop adding them is over, but not during the loop (everything looks fine while the loop is running) :



Public Class MyCustomType

Private Shared DefaultProperties As New Dictionary(Of String, Object) From {{"Number", -1},{"Name", "New Instance"}}

Public Property Number As Integer
Public Property Name As String

Sub New(NewInstanceProps As Dictionary(Of String, Object)

For Each Prop In NewInstanceProps

CallByName(Me, Prop.Key, CallType.Set, Prop.Value)

Next

End Sub



Sub New()


For Each Prop In DefaultProperties

CallByName(Me, Prop.Key, CallType.Set, Prop.Value)

Next

End Sub
End Class

Sub Main()

Dim Stash As New Dictionary(Of Integer, MyCustomType)

'50 randoms
For i=0 to 49
Dim randoms As New Dictionary(Of String, Object) From {{"Number", randomunique()},{"Name", randomname()}}
Dim holdVar As New MyCustomType(randoms)
Stash.Add(holdVar.Number, holdVar)
Next

For Each pair in Stash
Line(CStr(pair.Key), pair.Value.Name)
Next
End Sub


This code throws Object not set to instance when it gets printing the Name property. When I look inside the Stash dictionary, all entries are there, but Name property of each one is Nothing. However, inside the loop those properties are generated, assigned, stored and retreived from dictionary wuthout problems. But when I try to do anything with that dictionary outside the loop, exception is thrown.






Aucun commentaire:

Enregistrer un commentaire