The tiny VB.NET quiz – byref or what the…?

Alright, here is the next quiz. Imagine the following code:

Module Module1

    Dim intVal As Integer = 10
    Dim dblVal As Double = 20

    Sub Main()


    End Sub

    Private Sub PrintValues()
        Console.WriteLine("{0} - {1}", intVal, dblVal)
    End Sub

    Private Sub ModifyValue(ByRef Value As Integer)
Value = 30
    End Sub


This code will print out the following:

30 - 20
30 - 20
30 - 30

So why's that? Give it your best shot!


Comments (2)

  1. Because ModifyValue takes an integer by ref, the first call makes the change to the intVal as we would expect.  The printed value supports that.

    30 – 20

    First glance you would expect the second call to 30 – 20 but it does not.  The by ref value passed in has to be converted to an int for the function.  So during the function call it acts like a by val call, only passing the value.

    Once the funciton call ends, the by ref value gets updated.

    So its the converting from int to double and back that create this ghost effect.   Its more effecient to handle the update at the end of the call.  Keeping the original dblVal updated during the call would introduce too much overhead.

    Was I close?

  2. Kevin,

    I couldn’t have explained it better. Well done! Well done!

    The first type of reference parameter passing is called "true byref" whereas the second parameter passing is called "copy-in/copy-out".



Skip to main content