Mark Kramer
Mark Kramer

Reputation: 3214

How to get functions to not evaluate the return until the end

I have functions in my program that stop after it reaches a Return line but I need the function to continue in case what I want the function to return changes.

Is there a workaround for this or a way to force the function to continue after a return?

I made a Test Program to demonstrate the problem. It is a Form that contains only a button.

Here is the source code:

Private Sub btnTest_Click(sender As System.Object, e As System.EventArgs) Handles btnTest.Click
    If testFunction() = True Then
        MsgBox("It returned True!")
    Else
        MsgBox("It returned False!")
    End If
End Sub

Function testFunction() As Boolean
    Dim testVariable As Boolean = True
    Return False
    If testVariable = True Then
        Return True
    End If
End Function

The messagebox always says "It returned False" when if it continued going through the code like I want it to it would have returned true.

Upvotes: 0

Views: 195

Answers (3)

Mike Weber
Mike Weber

Reputation: 311

You could also do:

Function testFunction() As Boolean
  Dim testVariable As Boolean = True
  Return testVariable
End Function

Since testVariable is a boolean and the return type is boolean.

Upvotes: 0

reshma k
reshma k

Reputation: 544

Private Sub btnTest_Click(sender As System.Object, e As System.EventArgs) Handles btnTest.Click
    If testFunction() Then
        MsgBox("It returned True!")
    Else
        MsgBox("It returned False!")
    End If
End Sub  

Function testFunction() As Boolean
  Dim testVariable As Boolean = True
    If testVariable Then
        Return True
    End If
    Return False
End Function

Upvotes: 0

Ry-
Ry-

Reputation: 225273

You already have a flag variable set up, so use it!

Function testFunction() As Boolean
    Dim testVariable As Boolean = True
    testVariable = False

    Return testVariable
End Function

Also, don't ever use = True or = False in comparisons. = True is 100% redundant and x = False should be Not x.


EDIT: Sorry, that wasn't clear.

If x = True Then
    ' ...
End If

is always* the same as

If x Then
    ' ...
End If

Upvotes: 2

Related Questions