dragonwell
Programmer
OK, this is very embarrasing, having used VB.NET for almost two years now, and thinking I knew the difference between ByVal and ByRef in passing parameters.
The way I understand it, if you pass a reference type to a function ByVal, you are passing the reference to that object (and not a by-value copy). This seems to make sense by this test:
OK, now what about this:
What!? If in Sub Test, I have a reference to the instance of MyClass, should I not be able to destroy that reference as well??
I just don't get it.
The way I understand it, if you pass a reference type to a function ByVal, you are passing the reference to that object (and not a by-value copy). This seems to make sense by this test:
Code:
Class MyClass
Public Name As String = ""
End Class
Sub Test(ByVal x as MyClass)
x.Name = "Name Set ByVal"
End Sub
Sub Main()
Dim instance as MyClass = new MyClass()
Test(instance)
Console.WriteLine(instance.Name)
End Sub
[green]'output: Name Set ByVal[/green]
OK, now what about this:
Code:
Class MyClass
Public Name As String = ""
End Class
Sub Test(ByVal x as MyClass)
x.Name = "Name Set ByVal"
[b]x = Nothing[/b]
Sub Main()
Dim instance as MyClass = new MyClass()
Test(instance)
Console.WriteLine(instance.Name)
End Sub
[green]'output: Name Set ByVal
'expected: Null Reference Exception[/green]
What!? If in Sub Test, I have a reference to the instance of MyClass, should I not be able to destroy that reference as well??
I just don't get it.