Value not Change !

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi,

I wrote codes like this:

private structure ST
dim a as string
dim b as integer
end structure

dim arrST as new arraylist
for i as integer = 0 to 5
dim ST1 as ST
ST1.a = today.ToLongTimeString
ST1.b = i
arrST.add(ST1)
next

' the value of ST1.B in arrST will be 0 to 5

for i as integer = 0 to 5
dim ST1 as ST = arrST(i)
ST1.b += 1
next

' the value of ST1.B in arrST still 0 to 5

Can anyone help me, thanks!
 
It's because a struct is a value type.

Your line

Dim ST1 As ST = arrST(i)

is actually making a new ST and copying the values. It is not an object
reference to the original ST.

If you define ST as a class instead of a struct, you should get the
behaviour you want.
 
Hi Pony,

I think "Reg Edit" has pointed out the root cause for you. So your code in
the for loop only changes the new ST structure's b values, the original
copy of ST did not change at all.

There are 2 ways to resolve this:
1. Declare ST as class instead of structure, which will make ST into
reference type
2. Copy the new ST's changed value into the original ST copy in arrST. We
only need to add an extra line code to your original code:

For i As Integer = 0 To 5
Dim ST1 As ST = arrST(i)
ST1.b += 1
arrST(i) = ST1 ' Adding this line to your original code
Next

Hope this helps.

Best regards,
Jeffrey Tan
Microsoft Online Community Support
==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscriptions/managednewsgroups/default.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscriptions/support/default.aspx.
==================================================
This posting is provided "AS IS" with no warranties, and confers no rights.
 
Back
Top