If I were to use a class, I would do it something like this:
Public Class MyReturnType Private _value As Object Private _valueType As Type Public Sub New() _value = New Object _valueType = GetType(Object) End Sub Public Sub New(value As Object, valueType As Type) _value = value _valueType = valueType End Sub Public ReadOnly Property Value As Object Get Return _value End Get End Property Public ReadOnly Property ValueType As Type Get Return _valueType End Get End Property End Class
Then you can:
Public Function TrySomething(ByVal Param As String) As MyReturnType If Param <> "MAGICWORD" Then Return New MyReturnType(False, GetType(Boolean)) Else Return New MyReturnType("You Win!", GetType(String)) End If End Function
And all is well:
Sub DoSomethingWithReturnValue() Dim returnValue As MyReturnType = TrySomething("MAGICWORD") If returnValue.ValueType = GetType(Boolean) Then DoSomethingWithABoolean(CType(returnValue.Value, Boolean)) Else DoSomethingWithAString(CType(returnValue.Value, String)) End If End Sub
Personally, however, I do not think this is a good design. If you need to handle multiple types, use overloads or multiple functions. In your case, this is a simple “value or bust” situation, so I would just throw an exception and handle it, which should do in .NET.
source share