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?
Returning from a Function When the Function procedure returns to the calling code, execution continues with the statement that follows the statement that called the procedure. To return a value from a function, you can either assign the value to the function name or include it in a Return statement.
In visual basic, the Return statement is useful to terminate the execution of the method in which it appears and return the control back to the calling method. Generally, in visual basic, the Return statement is useful whenever we want to value the other methods.
When a return statement is used in a function body, the execution of the function is stopped. If specified, a given value is returned to the function caller. For example, the following function returns the square of its argument, x , where x is a number. If the value is omitted, undefined is returned instead.
To return a value from a function, you must include a return statement, followed by the value to be returned, before the function's end statement. If you do not include a return statement or if you do not specify a value after the keyword return, the value returned by the function is unpredictable.
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.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With