VB.NET Function Return

79,233

Solution 1

There is probably no difference. IIRC, the compiler generated IL converts them both into Return statements unless there is additional usage of a _returnValue variable.

The readability of the FunctionName assignment is poor in my opinion, and an example of a bad VB6 habit. I prefer the _returnValue (NOT RETVAL) variable method also.

Solution 2

The difference is that they DO DIFFERENT THINGS!

'Return value' does 2 things:
1. It sets the function return value at that point 2. It immediately exits the function

No further code in the function executes!

'Functionname = value' does 1 thing: 1. It sets the function return value at that point

Other code in the function continues to execute This enables additional logic to refine or override the function return value

Huge difference folks. Remember it's not all about state, it's also about flow.

Solution 3

Let's take a look... Oddly the "functionName =" generates less IL?

Code:

Public Function Test() As String
    Test = "Test"
End Function


Public Function Test2() As String
    Return "Test"
End Function

IL:

.method public static string Test() cil managed
{
    .maxstack 1
    .locals init (
        [0] string Test)
    L_0000: nop 
    L_0001: ldstr "Test"
    L_0006: stloc.0 
    L_0007: ldloc.0 
    L_0008: ret 
}

.method public static string Test2() cil managed
{
    .maxstack 1
    .locals init (
        [0] string Test2)
    L_0000: nop 
    L_0001: ldstr "Test"
    L_0006: stloc.0 
    L_0007: br.s L_0009
    L_0009: ldloc.0 
    L_000a: ret 
}

Solution 4

Doing the following is only provided for Visual Basic 6.0 developers to easily port code over:

Public Function MyFunction() As String
    MyFunction = "Hello"
End Function

I would definitely not recommend keeping doing it if your project includes anyone who hasn't worked with Visual Basic 6.0, as this syntax will be confusing.

Solution 5

99 times out of 100 I'll use "return value".

Every once in a while I'll have a function where the other type not only allows me to save a variable declaration, but do it in a way that actually significantly clarifies the function. Usually this happens when I would want to name the return value the same as the function anyway, and often these are recursive functions; something about that construct lends it to the implicit return variable. However, that scenario is extremely rare. I don't know if I have any functions using implicit return variables at all in my current project.

Share:
79,233
user50612
Author by

user50612

Updated on May 31, 2020

Comments

  • user50612
    user50612 almost 4 years

    In order to return a value from a VB.NET function one can assign a value to the "Functions Name" or use "return value."

    I sometimes see these inter-mixed in the same function. Personally, I prefer the return.

    My question is, what is the internal difference, if any, between the two?