vb.netpropertiesfunction-callbyref

Calling function with property as byref argument causes set method call


When calling a function with a property as an argument that's declared byref, the property's set method is executed after the function call.

This tosses a compiler error if done in c# if you try to pass a property into a function with ref, but in vb.net this goes through. Is this a bug? What's going on?

Module Module1

    Private _testProp As Integer
    Property testProp As Integer
        Get
            Return _testProp
        End Get
        Set(value As Integer)
            Console.WriteLine("changed TestProp to " & value.ToString())
            _testProp = value
        End Set
    End Property

    Private Sub testFunction(ByRef arg As Integer)
        Console.WriteLine(arg)
    End Sub

    Sub Main()
        Console.WriteLine("explicit set to 5 in main")
        testProp = 5
        Console.WriteLine("calling function")
        testFunction(testProp)
        Console.ReadKey()
    End Sub

End Module

Output:

explicit set to 5 in main
changed TestProp to 5
calling function
5
changed TestProp to 5


Solution

  • Passing a property to a ByRef parameter results in the property being passed by copy-in/copy-out. The VB language specification states,

    Copy-in copy-back. If the type of the variable being passed to a reference parameter is not compatible with the reference parameter's type, or if a non-variable (e.g. a property) is passed as an argument to a reference parameter, or if the invocation is late-bound, then a temporary variable is allocated and passed to the reference parameter. The value being passed in will be copied into this temporary variable before the method is invoked and will be copied back to the original variable (if there is one and if it's writable) when the method returns.

    So this is clearly by design and not a bug.