ByVal vs. ByRef

  • Thread starter Thread starter Chris
  • Start date Start date
C

Chris

Sorry for the newbie question. I'm passing around a database connection
into several forms. Do I use byref or byval for the variable, and why?
To me I should use byref, since I don't want a copy of the connection....

thanks
Chris

Public Sub New(ByVal MySqlConn As MySqlConnection)
MyBase.New()

'This call is required by the Windows Form Designer.
InitializeComponent()
Conn = MySqlConn
'Add any initialization after the InitializeComponent() call

End Sub
 
Chris said:
Sorry for the newbie question. I'm passing around a database connection
into several forms. Do I use byref or byval for the variable, and why?
To me I should use byref, since I don't want a copy of the connection....

See http://www.pobox.com/~skeet/csharp/parameters.html

It's about C#, but I believe all the same principles apply to VB.NET.
In short, use ByVal - you're not creating copies of the *object*, just
new references which "point" to the object.
 
It would never be a copy of the actual connection. ByVal would mean it is a
copy of the *reference* to that connection. In either case there is only
ever 1 connection object.

The ByVal 'copy' can only happen with value types (integers, booleans, etc).
 
Marina said:
It would never be a copy of the actual connection. ByVal would mean it is a
copy of the *reference* to that connection. In either case there is only
ever 1 connection object.

The ByVal 'copy' can only happen with value types (integers, booleans, etc).

Ahh, copy the reference not the object, that makes sense now....

Chris
 
Reference Type passed ByVal (the most common scenario) = Copy of the
reference, not the object
Reference Type passed ByRef = Pointer to the original reference
Value Type passed ByVal = Copy of the value type
Value Type passed ByRef = Pointer to the original value type
 
Back
Top