views:

48

answers:

2

I have a Dictionary with key of type UInteger and the value is List(Of Session) where the (Public) class Session contains a couple of variables and a constructor (Public Sub New(...)).

Some of the variables in my Session class is:

Private count As Integer
Private StartDate As Date
Private Values As List(Of Integer)

and a couple of methods like:

Friend Sub Counter(ByVal c as Integer)
    count += c
End Sub

There is no problem to add values to the Dictionary:

Dim Sessions As New List(Of Session)
Dim dict As New Dictionary(Of Integer, List(Of Sessions))

then some code to fill up a couple of Session objects in Sessions (not shown here) and then:

dict.Add(17, Sessions) ''#No problem
Sessions.Clear()
Sessions = dict(17) ''#This doesn't return anything!

The Sessions object is empty even if the code doesn't returned any error. Is my class Session to compex to be stored in a Dictionary?

+4  A: 

That's because the Sessions variable is a reference to the data, so when you add it to the dictionary, the one in the dictionary is pointing to the same thing. So when you do Sessions.Clear() you clear the actual data and since both the references point at the same place, neither of them now hold the data.

If you actually want to have two different copies of the data, this discussion might be helpful.

ho1
Thanks, I understand! Is the generic answer that every time you add a class to a Collection of any kind you pass a reference type and need to handle the copying or cloning manually?
Magnus
@magsto: Yes, that is the way you have to handle all reference types.
ho1
+1  A: 

These lines seem fishy to me:

Dim Sessions As New List(Of Session)

' Your Sessions variable has the same name as a class? '
Dim dict As New Dictionary(Of Integer, Sessions)

' You are adding a List(Of Session) to a Dictionary(Of UInteger, Sessions)? '
' This could only be legal if List(Of Session) derived from your Sessions class '
' (which is obviously not true). '
dict.Add(17, Sessions)

It's also confusing what exactly you mean here:

Sessions.Clear()
Sessions = dict(17) 'This does not return anything!'

By "doesn't return anything," do you mean it returns Nothing or an empty List(Of String)? In the latter case, that's expected: you just cleared the very list you're talking about. In the former case, that is very strange, and we'll need more details.

Dan Tao
Sorry for that, it should be Dim dict As New Dictionary(Of Integer, List(Of Session)) as Marc pointed out above.
Magnus