Home United States USA — software An End to Co-Evolution with Visual Basic 15

An End to Co-Evolution with Visual Basic 15

266
0
SHARE

Visual Basic 15 brings with it partial implementations of two important C# features: tuples and ref returns. Neither feature is “complete”, but they do offer enough work-arounds that VB applications can consume C# libraries that make use of these features.
Visual Basic 15 brings with it partial implementations of two important C# features: tuples and ref returns. Neither feature is “complete”, but they do offer enough work-arounds that VB applications can consume C# libraries that make use of these features.
Tuples
The ability to directly return multiple values from a single function call has long been a requested feature in VB. Although you can get the same result using ByRef parameters, the syntax is clumsy compared to what you see in functional programming languages.
If you aren’t familiar with the term, a “tuple” is just a set of related values. Since. NET 4.0, Visual Basic has had a standard Tuple class , but the user experience has been less than satisfactory. The values have to be manually unpacked from the Tuple using the unhelpful property names Item1, Item2, etc.
Seven years later, VB 15 finally adds syntax support for tuples. Or rather, the ValueTuple structure, which offers better performance than the heap-allocated Tuple object. Here is an example of a TryParse method written using the new style:
Public Function TryParse(s As String) As (Boolean, Integer)
Try
Dim numericValue = Integer. Parse(s)
Return (True, numericValue)
Catch
Return (False, Nothing)
End Try
End Function
Dim result = TryParse(s)
If result. Item1 Then
WriteLine(result. Item2)
End If
In this example, the return type of TryParse is ValueTuple. This makes the function a bit cleaner as you never have to explicitly mention the ValueTuple type. But as you can see, the code that calls it isn’t any different. So let’s improve it a bit by renaming the fields on the return type:
Public Function TryParse(s As String) As (IsInteger As Boolean, Value As Integer)

End Function
Dim result = TryParse(s)
If result. IsInteger Then
WriteLine(result. Value)
End If
You can create new tuples with named fields using this syntax:
Dim kvPair = (Key := 5, Value := « Five »)
Unfortunately there isn’t a way to “unpack” a tuple in VB into multiple variables. So translating this C# code into VB requires one line per variable.
var (key, value) = kvPair;
(By)Ref Returns
Ref returns, known as ByRef returns in VB, are severely limited.

Continue reading...