Home > Blockchain >  How do I access a returned variable from a different function within a function?
How do I access a returned variable from a different function within a function?

Time:10-12

I have a function "A" that retrieves an integer value from a textbox in SSRS:

Dim currasm As Integer = Nothing
Function GetAsmCurrent(ByVal currasm As Integer) As Integer
    Return currasm
End Function

...and a second function "B" where I would like to use the value returned from function "A".

Dim lastsn As String = Nothing
Function GetSN(ByVal currentsn As String) As String
    Dim currasm1 As Integer = Nothing
    ' <------ Here is where I thought I could call the function ------>
    currasm1 = GetAsmCurrent(currasm)
    ' <--------------------------------------------------------------->
    If Not currasm1 = Nothing And currentsn = Nothing Then "NO SN"
    ElseIf Not currentsn = Nothing Then
        lastsn = currentsn
    End If
    Return lastsn
End Function

It always pulls a 0 in, instead of 1, 2, etc. depending on the assembly number in the textbox on the report page.

CodePudding user response:

Private currasm As Integer 
Function GetAsmCurrent(ByVal currasm As Integer) As Integer
    Return currasm
End Function

This function will return the value passed to it, not the class level variable. The code will always seek the variable in the closest scope. Sort of silly to return what is passed. Again, as I stated in comments, a value type has a default value, in this case 0 and cannot be set to Nothing unless nullable. It is customary to use Private instead of Dim for class level variables.

Private lastsn As String = Nothing

Function GetSN(ByVal currentsn As String) As String
    Dim currasm1 As Integer 
    currasm1 = GetAsmCurrent(currasm)
    If Not currasm1 = 0 And currentsn = Nothing Then
        currentsn = "NO SN" 
    ElseIf Not currentsn = Nothing Then
            lastsn = currentsn
    End If
    Return lastsn
End Function

In this function GetAsmCurrent(currasm) will pass the value of the class level variable and return the same value. Might be easier to just say currasm1 = currasm assuming the 2 functions are in the same class. As discussed above currasm1 cannot be Nothing.

This will not compile "NO SN". What could that possibly mean? Did you intend to assign that string to some variable? I will assume you intended to assign it to currentsn.

If you are calling this function within the same class, it can be a Sub. Any method in the class can access class level variables.

  • Related