6

I'm just going through our codebase at work, trying to clear the Warnings that get generated when compiled and there are a ton of "Function without As clause, clause" warnings.

While going back and changing most of these to be a Sub instead of a Function, I occasionally overlook a Return statement because I just highlight the method name and look for a value assigned to it, which is how it's done in most of the code.

So I was just wondering if there's any difference between these:

Private Function Foo() As String
    Foo = String.Empty
End Function

Or:

Private Function Foo() As String
    Return String.Empty
End Function

Functionally, it seems to be identical but I wasn't sure if there was any behind the scenes differences in regards to how the compiler interprets this.

3 Answers 3

6

The main difference is that Return exits the function while assigning a value to the function name does not. So the two equivalents should be

Private Function Foo() As String
    Foo = String.Empty
    Exit Function
    '.....
End Function

Or:

Private Function Foo() As String
    Return String.Empty
    '.....
End Function
1
  • Oh, fair enough yea. I know return exists immediately, I just wasn't sure if there was anything else going on behind the scenes with how the variables are handled or anything of that nature.
    – sab669
    Aug 17, 2015 at 12:36
3

There's no significant difference.

However, I prefer using Return <variable> as it's much clearer in terms of code readability. Of course that's a personal preference.

It also lessons the possibility of stepping on another variable with the same name.

3

As far as flow control statements go, they're not necessarily identical, though the two examples given would behave identically.

When you do this:

Return String.Empty

The function exits and the result of the function is the supplied value. When you do this:

Foo = String.Empty

The result of the function is the supplied value, but the function does not exit. You can do something like this:

Foo = String.Empty
' other logic
Foo = someValue

If the function exited somewhere in other logic, such as from an Exit Function statement, then its result would have been String.Empty since that was the last value set as the result. If it didn't, then its result would be someValue because that would be the last value set as the result.

They're used for similar purposes, returning values from the function. But the flow (and subsequent readability) of the code can be quite different depending on how they're used.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.