dreamprisoner
dreamprisoner

Reputation: 11

VB.NET Boxing weirdness

I can't understand what is happening with the following code in VB.NET. When I run this code:

Public Function test() As Boolean
    Dim  a As Integer = 1
    Dim b As Object = a
    Dim c As Object = b
    Return Object.ReferenceEquals(b, c)
End Function

Then the function returns True. However, if I run this:

Structure TTest
    Dim i As Integer
    Dim tid As Integer
    Sub New(ByVal _i As Integer, ByVal _tid As Integer)
        i = _i
        tid = _tid
    End Sub
End Structure

Public Function test_2() As Boolean
    Dim a As New TTest(1, 1)
    Dim b As Object = a
    Dim c As Object = b
    Return Object.ReferenceEquals(b, c)
End Function

Then it returns False. In both functions, I declare two value type variables, an Integer on the first and a custom Structure on the second one. Both should be boxed upon object assignment, but in the second example, it seems to get boxed into two different objects, so Object.ReferenceEquals returns False.

Why does it work this way?

Upvotes: 1

Views: 144

Answers (2)

the_lotus
the_lotus

Reputation: 12748

Same with strings, it's .NET way to optimize thing. But as soon as you use it, the reference will change.

Sub Main()

    Dim a As String = "abc"
    Dim b As String = "abc"

    Console.WriteLine(Object.ReferenceEquals(a, b)) ' True

    b = "123"

    Console.WriteLine(Object.ReferenceEquals(a, b)) ' False

    Console.ReadLine()

End Sub

Upvotes: 0

Joel Coehoorn
Joel Coehoorn

Reputation: 415931

For primitive types, .Net is able to re-use the same "box" for the same values, and thus improve performance by reducing allocations.

Upvotes: 1

Related Questions