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.
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
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With