Barrett,
"barrett bonden" <ar**********@yahoo.com> schrieb:
Is there any way to pass parameters to a function and simply know there
will
get there without the silly (C like ) complexity of worring about byval
and
or perhaps byref ?
In VB.NET, 'ByVal' is the default (opposed to VB6, where 'ByRef' was the
default), so you don't need to explicitly specify it. 'ByVal' and 'ByRef'
serve slightly different purposes for value types and reference types:
When passing a variable to a method in a 'ByVal' parameter, the variable's
content is duplicated and the copy is passed to the method. Altering the
parameter variable inside the method won't change the variable you passed to
the method. On the other hand, 'ByRef' will pass a "reference" to the
variable to the method, and thus assigning another value to the parameter
variable inside the method will affect the value of the variable passed to
the method:
\\\
Dim i As Integer = 2
DoSomething1(i)
MsgBox(CStr(i)) ' "2".
i = 2
DoSomething2(i)
MsgBox(CStr(i)) ' "3".
..
..
..
Private Sub DoSomething1(ByVal i As Integer)
i = i + 1
End Sub
Private Sub DoSomething2(ByRef i As Integer)
i = i + 1
End Sub
///
For reference types (classes) there is also a difference between 'ByVal' and
'ByRef'. By passing a variable to a parameter that is marked as 'ByVal', a
copy of the reference stored in the variable is created and this reference
is passed to the method. Thus you cannot change the reference the variable
you passed to the method is pointing to inside the method ('DoSomething1').
When passing the variable 'ByRef', the variable's reference is exposed to
the method directly and can be manipulated by the method, which means that
the method can let the variable you passed to the method point to another
object. The sample below will demonstrate this behavior:
\\\
Dim sb As New StringBuilder("Foo")
DoSomething1(sb)
MsgBox(sb.ToString()) ' "Foo".
sb = New StringBuilder("Foo")
DoSomething2(sb)
MsgBox(sb.ToString()) ' "Bla".
..
..
..
Private Sub DoSomething1(ByVal s As StringBuilder)
s = New StringBuilder()
s.Append("Bla")
End Sub
Private Sub DoSomething2(ByRef s As StringBuilder)
s = New StringBuilder()
s.Append("Bla")
End Sub
///
--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://dotnet.mvps.org/dotnet/faqs/>