VB.NET Function Return

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?


Solution 1:

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 2:

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 3:

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.