ByRef vs ByVal generates errors!?
I had a method that used an Object
Function Foo(ByRef bar as CustomObject) as Boolean
this method generated errors, because some strange .NET Runtime things changed the bar object, causing its Dispose()al.
A lot of time spent to understand the thing(where the … object is changed), until somebody replaced ByRef by ByVal and object wasn’t change anymore when passing to this method…
Somebody could explain this, what happens?
Nota Bene (edit)
As in my case the function Foo does NOT modify the bar, shouldn’t ByRef or ByVal have the same effect?
The Foo just read the Properties from bar.
Code:
Module Module1
Sub Main()
Dim b As New Bar
' see the output bellow '
Foo(b.Name)
Console.ReadLine()
End Sub
Function Foo(ByRef name As String) As Boolean
Console.WriteLine("Name is : '{0}'", name)
End Function
Class Bar
Private _Name As String = "John"
Property Name()
Get
Return _Name
End Get
Set(ByVal value)
If _Name IsNot Nothing Then
'_Name.Dispose() If this were an IDisposable, would have problems here'
End If
Console.WriteLine("Name is Changed to '{0}'", value)
End Set
End Property
End Class
End Module
Output:
Name is : ‘John’
Name is Changed to ‘John’
In VB.NET, passing a property by reference updates the actual property, not the underlying value. Thus, when Foo completes, the CLR calls the Property Set method to update the property value with whatever the new value is at the end of the function (even if it hasn’t changed).
This behaviour is described in the VB.NET Language Specification (Reference Parameters section, last 3 paragraphs):
http://msdn.microsoft.com/en-us/library/aa711958(v=VS.71).aspx