Shared function - strange behaviour

  • Thread starter Thread starter Hayrob
  • Start date Start date
H

Hayrob

I have extracted the code fragment below. The variables do not appear to be
set, which is not what I expected. I can see it must be a problem with a
Shared method and an instance object, but I cann't understand exactly what
is happening - any advice?

Thanks

Robin Hay

Module Module1

Public Class SomeClass

Inherits CollectionBase

Public Structure Thing

Private mFirstThing As String

Private mSecondThing As String

Public Property FirstThing() As String

Get

Return mFirstThing

End Get

Set(ByVal Value As String)

mFirstThing = Value

End Set

End Property

Public Property SecondThing() As String

Get

Return mSecondThing

End Get

Set(ByVal Value As String)

mSecondThing = Value

End Set

End Property

End Structure

Default Public ReadOnly Property Item(ByVal Index As Integer) As Thing

Get

Return CType(list.Item(Index), Thing)

End Get

End Property

Public Sub Add(ByVal theThing As Thing)

List.Add(theThing)

End Sub



Public Shared Function AddThings() As SomeClass

Dim theSomeClass As New SomeClass

Dim theThing As New Thing

theSomeClass.Add(theThing)

For Each theThing In theSomeClass

theThing.FirstThing = "One"

theThing.SecondThing = "Two"

Next

Return theSomeClass

End Function

End Class

Sub Main()

Dim theClass As SomeClass = SomeClass.AddThings

Console.WriteLine("First Thing: {0} Second Thing: {1}",
theClass(0).FirstThing, theClass(0).SecondThing)

Console.ReadLine()

End Sub

End Module
 
Hayrob said:
Public Shared Function AddThings() As SomeClass
Dim theSomeClass As New SomeClass
Dim theThing As New Thing
theSomeClass.Add(theThing)
For Each theThing In theSomeClass
theThing.FirstThing = "One"
theThing.SecondThing = "Two"
Next
Return theSomeClass
End Function


"Thing" is a structure. A structure is a value type. Whenever you execute

For Each theThing In theSomeClass

the items in theSomeClass are copied to the variable theThing. As it is a
*copy* of the item in the list, changing the properties of the copy doesn't
change the properties of the item in the list.

The only solution is to make a class instead of a strucutre. A class is a
reference type. Consequently, "For Each" gets copies of the *references* of
the items in the list.
 
Back
Top