Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VB function with multiple output - assignment of results

I know there's no straightforward way for multiple assignment of function in VB, but there's my solution - is it good, how would you do it better?

What I need (how would I do it in python, just an example)

def foo(a)    ' function with multiple output
    return int(a), int(a)+1

FloorOfA, CeilOfA = foo(a) 'now the assignment of results

How I do it in VB:

Public Function foo(ByVal nA As Integer) As Integer() ' function with multiple output
    Return {CInt(nA),CInt(nA)+1}
End Function

Dim Output As Integer() = foo(nA) 'now the assignment of results
Dim FloorOfA As Integer = Output(0)
Dim CeilOfA As Integer = Output(1)
like image 644
Intelligent-Infrastructure Avatar asked May 08 '13 09:05

Intelligent-Infrastructure


People also ask

How can a function return multiple values in VB?

A function in VB.NET can only return one value—this can be a value type or a reference type (like a Class). But one value is not always sufficient. With ByRef arguments, we can set multiple output values. And with a structure like KeyValuePair (or a class like Tuple) we can return multiple values as one.


1 Answers

For future readers, VB.NET 2017 and above now supports value tuples as a language feature. You declare your function as follows:

Function ColorToHSV(clr As System.Drawing.Color) As (hue As Double, saturation As Double, value As Double)
  Dim max As Integer = Math.Max(clr.R, Math.Max(clr.G, clr.B))
  Dim min As Integer = Math.Min(clr.R, Math.Min(clr.G, clr.B))

  Dim h = clr.GetHue()
  Dim s = If((max = 0), 0, 1.0 - (1.0 * min / max))
  Dim v = max / 255.0

  Return (h, s, v)
End Function

And you call it like this:

Dim MyHSVColor = ColorToHSV(clr)
MsgBox(MyHSVColor.hue)

Note how VB.NET creates public property named hue inferred from the return type of the called function. Intellisense too works properly for these members.

Note however that you need to target .NET Framework 4.7 for this to work. Alternately you can install System.ValueTuple (available as NuGet package) in your project to take advantage of this feature.

like image 97
dotNET Avatar answered Oct 28 '22 12:10

dotNET