Reputation: 155
My question is regarding the concept for working of ByVal in vb.net.
Here is the code:
Private Sub ManipulateDetails()
Dim tObject1 as New customdatatype
tObject1.sName = "Stack"
tObject1.sLastName = "Over"
GetManipulateDetails(tObject1)
End Sub
Private Function GetManipulateDetails(ByVal tObject1 as customdatatype)
tObject1.sName = "Stack-Over-Flow"
tObject1.sLastName = "Flow-Over-Stack"
Return tObject1
End Function
In the above code snippet I am sending tObject1 as ByVal in the GetManipulateDetails function, when the values are changed in this subroutine the object which is returned back, manipulates the actual object which was passed. i.e. if I quickwatch the object in the method ManipulateDetails I can see the manipulated details. Also if I am returning the object in the subroutine function the value is getting reflected in the original object which was passed.
as the value is getting changed even without returning the object from the function GetManipulateDetails, I am confused whether this is happening because of ByRef?? or there is some other mechanism which is making this work.
Upvotes: 0
Views: 1908
Reputation: 239764
It may be clearer if we use different names:
Private Sub ManipulateDetails()
Dim tObject1 as New customdatatype
tObject1.sName = "Stack"
tObject1.sLastName = "Over"
GetManipulateDetails(tObject1)
End Sub
Private Function GetManipulateDetails(ByVal tother as customdatatype) as customdatatype
tother.sName = "Stack-Over-Flow"
tother.sLastName = "Flow-Over-Stack"
Return tother
End Function
Before you call GetManipulateDetails
, tObject1
is a reference to an object of type customdatatype
. When you call GetManipulateDetails
, tother
gets a copy of tObject1
. Importantly, what this means is that now, tObject1
and tother
are both references to the same object. What was copied was the reference, not the object. Within GetManipulateDetails
, it can use its copy of the reference to access the object and make changes to it.
ByVal
parameters are always copied - but parameters are either value types or references. They're never reference types (aka objects) themselves.
Upvotes: 3