Search code examples
vb.netpointersvalue-typebyref

VB.NET Pointer to value types


VB.NET 2010, .NET 4

Hello all,

I'm by no means a good programmer and I'm just trying to wrap my head around some of this stuff, so please forgive me if this is a dumb question.

I want the following to produce a message box that says "2", not "5":

Public Class SomeClass
  Private SomeInt As Integer = 5
  Private SomeListOfInts As New List(Of Integer)

  Public Sub New()
    SomeListOfInts.Add(SomeInt)
    SomeListOfInts(0) = 2
    MsgBox(SomeInt.ToString)
  End Sub
End Class

This doesn't work. The message box says "5". I think that I understand why to some degree. Since SomeInt is a value type, adding it to SomeListOfInts just adds a copy. I'm sorry if this is incoherent. Is there any straightforward way to accomplish this?

Thanks in advance, Brian

Edit: I just wanted to add, I suspect folks'll say "Why try to do this?"/"This is not a good thing to try to do." etc. I'm alright with that and would like to know a better approach if there is one, however, I am also generically curious about how something like this might be done, whether it's good practice or not. Also, if it isn't good practice (whatever that means), why?


Solution

  • It is output 5 because your MsgBox is referencing SomeInt, not SomeListOfInts(0)

    Try this:

    Public Class SomeClass
      Private SomeInt As Integer = 5
      Private SomeListOfInts As New List(Of Integer)
    
      Public Sub New()
        SomeListOfInts.Add(SomeInt)
        SomeListOfInts(0) = 2
        MsgBox(SomeListOfInts(0).ToString) // here is the change
      End Sub
    End Class
    

    This...

    SomeListOfInts(0) = 2
    

    changes indexed element 0 in your list from 5 (the original value of element 0) to 2. Also, int is a value type. Therefore, when you add SomeInt to the list, you have created a copy of the value type. The copy can be changed without affecting the original SomeInt.

    You could start with:

    Private ListOfInts As New List(Of Integer)

    Public Sub New(SomeInt As Integer)
        ListOfInts.Add(SomeInt)
    
        ' processes
    
        ListOfInts(0) = 2
        MsgBox(SomeListOfInts(0).ToString)
    End Sub
    

    Maybe with a little more background on exactly what you are trying to do, I can help you get closer to your expectations.