Search code examples
.netvb.netgenericstypeslate-binding

Set type of a variable using a condition


How to set type of a variable using a condition?
If I do like example below, my variable x is no more existing after the end if, here is my problem.

    If RequestedType = "Integer" Then
        Dim x As Integer
    Else
        Dim x As String
    End If

Solution

  • There is no such possibility. You would rather use the Overloading of Methods. I guess that you would do some processing with x. For example, you could have a call to an overloaded subroutine making the processing on x.

    Function ProcessMe(ByVal p_X As String) As Integer ' I assume you would return an Integer...
        ' Write here the processing on parameter p_X
    End Function
    
    Function ProcessMe(ByVal p_X As Integer) As Integer
        ' Call the previous method with p_X converted to string
        Return ProcessMe(p_X.ToString())
    End Function
    

    Then, in your code you coud write

    If RequestedType = "Integer" Then
        Dim x As Integer
        ProcessMe(x)
    Else
        Dim x As String
        ProcessMe(x)
    End If