Adagio
Well-known member
- Joined
- Dec 12, 2005
- Messages
- 162
- Programming Experience
- Beginner
From what I understand, this is how it works:
ByRef (a.k.a. By Reference) points to where the object is in the memory. Any changes made to the object sent ByRef should change the values of the original object
ByVal (a.k.a. By Value) points to a copy of the object. Any changes made to the object shouldn't change anything in the original object
Let's make an example:
This shows exactly how I understand the difference between ByVal and ByRef
But if we instead of using simple objects as Strings, there's no difference between ByVal and ByRef anymore. Just take a look at this example:
The second messagebox shows Baaaa - Buuuu instead of the expected A - Buuuu... but why is that? Apparently ByVal and ByRef does exactly the same thing. It seems like it sends the reference to the object when using ByVal, instead of making a new object
Anyone here who can tell me why this is?
ByRef (a.k.a. By Reference) points to where the object is in the memory. Any changes made to the object sent ByRef should change the values of the original object
ByVal (a.k.a. By Value) points to a copy of the object. Any changes made to the object shouldn't change anything in the original object
Let's make an example:
VB.NET:
Private Sub FormLoad()
Dim a As String = "A"
Dim b As String = "B"
MsgBox(a & " - " & b) ' This shows "A - B"
ChangeProperty(a)
ChangeRefProperty(b)
MsgBox(a & " - " & b) ' This shows "A - Buuuu"
End Sub
Private Sub ChangeProperty(ByVal b As String)
b = "Baaaa"
End Sub
Private Sub ChangeRefProperty(ByRef b As String)
b = "Buuuu"
End Sub
This shows exactly how I understand the difference between ByVal and ByRef
But if we instead of using simple objects as Strings, there's no difference between ByVal and ByRef anymore. Just take a look at this example:
VB.NET:
Private Sub FormLoad()
Dim a As New Bacon
Dim b As New Bacon
a.NewProperty = "A"
b.NewProperty = "B"
MsgBox(a.NewProperty & " - " & b.NewProperty) ' This shows "A - B"
ChangeProperty(a)
ChangeRefProperty(b)
MsgBox(a.NewProperty & " - "& b.NewProperty) ' This shows "Baaaa - Buuuu"
End Sub
Private Sub ChangeProperty(ByVal b As Bacon)
b.NewProperty = "Baaaa"
End Sub
Private Sub ChangeRefProperty(ByRef b As Bacon)
b.NewProperty = "Buuuu"
End Sub
Private Class Bacon
Private newPropertyValue As String
Public Property NewProperty() As String
Get
Return newPropertyValue
End Get
Set(ByVal value As String)
newPropertyValue = value
End Set
End Property
End Class
The second messagebox shows Baaaa - Buuuu instead of the expected A - Buuuu... but why is that? Apparently ByVal and ByRef does exactly the same thing. It seems like it sends the reference to the object when using ByVal, instead of making a new object
Anyone here who can tell me why this is?