Working with Byval and ByRef keywords
Hey,
Could anyone show me how to work with ByVal and ByRef Keywords in Visual Basic.Net ?
Thanks
Hey,
Could anyone show me how to work with ByVal and ByRef Keywords in Visual Basic.Net ?
Thanks
http://msdn.microsoft.com/msdnmag/issues/02/06/Instincts/
It's actually a long story and it's described well in the article above.
First of all Byval mens that your method receives a private copy of the object it's receiving. If you modify it, you are modifying the private copy, not the actual object. ByRef passes an address and not a copy. It's slightly slower since it is an indirection.
If you want to modify a value and pass it back, use ByRef. If you just want to read something and use it as a scratch pad use ByVal. BYVALs are associated with TYPES classes and other reference object are associated byval.
byval:
private sub DoDisplayMessage(ByVal theMessage as String)
MessageBox.Show(theMessage)
end sub
'Some button1 click event
Me.DoDisplayMessage("Hello! I pressed the button and now I am being called/shown from the DoDisplayMessage, giving this long message to the sub!")
ByRef:
private sub DoChangeMessage(ByRef theMessage as String)
theMessage = "Message modified at: " & DateTime.Now.ToString()
end sub
'some button click event
Dim myMessage as string = "hello"
MessageBox.Show("Before: " & myMessage)
Me.DoChangeMessage(myMessage)
MessageBox.Show("After: " & myMessage)
this article has a sample also
http://msdn2.microsoft.com/en-us/library/chy4288y.aspx
http://msdn2.microsoft.com/en-us/library/dz1z94ha.aspx