closures continued.. ByRef, ByVal and ()
Posted
Sat, Apr 8 2006 21:35
by
bill
A rarely used, somewhat obscure feature of VB, is by enclosing a variable in ()'s it is passed ByVal instead of ByRef. Consider the following code:
(1)
Dim s As String = "hello"
Foo(s)
Console.Writeline(s)
versus:
(2)
Dim s As String = "hello"
Foo((s))
Console.Writeline(s)
where Foo is defined as:
Sub Foo(ByRef value as string)
value = "goodbye"
End sub
In second case the output is "hello", whereas in the first case it is "goodbye", all due to one little ol' set of ()'s encompassing the variable s.
So we do already have a mechanism to achieve the ByVal approach I discussed in my previous post about closures. Btu the question we need to ask is "Is that desirable for VB?"
Let me give another example. Let's say I have a simple method as follows:
Sub Add100(ByRef x as Int32)
x +=100
End Sub
Now in a Form's code I could call that method like
Add100(Me.Left)
Add100((Me).Left)
Add100((Me.Left))
and in 2 of the above 3 cases the form would move 100 pixels to the right. Is that desirable ? How difficult is it to visualize the difference between those three examples and know which one is the odd one out ?
Now assuming this was also used to decouple local variables when in LINQ lambda expressions, then taking
Paul's example:
For i AsInteger = 0 To 2
Dim y AsInteger = i
queries(i) = Select x From x In xs Where x <= y
Next
we could dramatically change the output from that by adding just one set of ()'s
For i AsInteger = 0 To 2
Dim y AsInteger = i
queries(i) = Select x From x In xs Where x <= (y)
Next
but is that just a little too obscure? I think so.
I really feel the overloading of ()'s to mean so many different things in VB is one of it's major pains. This almost cryptic use of parenthesis is something I'd more expect in a punctuation pedantic language like C#, not VB. The code needs to be more visually distinct.
So let's try changing that a bit, visually:
For i AsInteger = 0 To 2
Dim y AsInteger = i
queries(i) = Select x From x In xs Where x <= (y)
Next
possible a bit too subtle still. Let's try adding the ByVal keyword
For i AsInteger = 0 To 2
Dim y AsInteger = i
queries(i) = Select x From x In xs Where x <= (ByVal y)
Next
that certainly sticks out a bit more :)
Let's try it on the other examples:
Add100(Me.Left)
Add100((ByVal Me).Left)
Add100((ByVal Me.Left))
Visually, I think adding the ByVal inside the ()'s makes all the difference. It moves punctuation into a spoken language. The
VB language specification agrees with this type of notation saying:
The Visual Basic programming language has a syntax that is similar to English, which promotes the clarity and readability of Visual Basic code. Wherever possible, meaningful words or phrases are used instead of abbreviations, acronyms, or special characters.
So there we have it folks. That's my opinion on the matter :)