Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to return multiple types in a VB .Net function? (not a Tuple, like PHP internal functions)

Tags:

.net

vb.net

So you know how PHP internal functions usually return a boolean FALSE when a function fails, or some other data type when the function succeeds? Is this possible in VB .Net?

For instance, lets say this simple code here

Public Function TrySomething(ByVal Param As String) \\what would go here??
    If Param <> "MAGICWORD" Then
        Return False
    Else
        Return "You Win!"
    End If
End Function

You see I want to return a BOOLEAN false when a function fails, and a string when the function works. Any ideas? I've looked everywhere, and when I search for "return multiple types" all I find is Tuple.

like image 633
Mike L. Avatar asked Dec 02 '22 23:12

Mike L.


2 Answers

You could use an object as Dan says. But then you have to check for the returned type in the calling routine.

Sub Checkit()
    Dim ret As Object = TrySomething("MAGICWORD")
    If TypeOf ret Is Boolean Then
        'dosomething
        MsgBox("Nope!")
    End If
    If TypeOf ret Is String Then
        'dosomethingelse
        MsgBox("Yes, you won!")
    End If

End Sub

Public Function TrySomething(ByVal Param As String) As Object
    If Param <> "MAGICWORD" Then
        Return False
    Else
        Return "You Win!"
    End If
End Function

I would not go that way, I would create a structure or class to handle exactly what I wanted instead. Like this:

Sub Checkit()
    Dim ret As TryReturnStruct = TrySomething("MAGICWORD")
    MsgBox(ret.Message)
    If ret.Success Then
        MsgBox("Do you want to play again?")
    End If
End Sub

Structure TryReturnStruct
    Public Success As Boolean
    Public Message As String
End Structure

Public Function TrySomething(ByVal Param As String) As TryReturnStruct
    Dim ret As New TryReturnStruct

    If Param <> "MAGICWORD" Then
        ret.Success = False
        ret.Message = "Nope, not yet!"
    Else
        ret.Success = True
        ret.Message = "You Win!"
    End If
    Return ret
End Function
like image 137
Stefan Avatar answered Dec 18 '22 23:12

Stefan


This will Work for you:

Public Function TrySomething(ByVal Param As String) As Object
If Param <> "MAGICWORD" Then
    Return False
Else
    Return "You Win!"
End If
End Function

You can check the values like this:

 Dim a As Boolean = TrySomething("")
 Dim b As String = TrySomething("MAGICWORD")
like image 27
Harsh Avatar answered Dec 18 '22 23:12

Harsh