VB.NET Function - Return vs Assignment
What is the difference between this two ways of returning value in a function in VB.NET?
Using Return Statement:
Public Function Foo() As String
Return "Hello World"
End Function
Using Assignment:
Public Function Foo() As String
Foo = "Hello World"
End Function
开发者_开发百科I'm using the first one then I saw someone using the second. I wonder if there's a benefit I could get using the second.
Its a legacy carry over from basic days.
Return
will leave the scope immediately, while assignment wont.
Think of it this way:
Public Function Foo() As String
Foo = "Hello World"
OtherFunctionWithSideEffect()
End Function
vs
Public Function Foo() As String
Return "Hello World"
OtherFunctionWithSideEffect()
End Function
Now can you see the difference?
In practice, modern VB.Net should almost always prefer the latter style (Return
).
Testing this in LinqPad:
Public Function myString() As String
Return "Hello World"
End Function
Public Function myString2() As String
myString2 = "Hello World"
End Function
Here's the IL output:
myString:
IL_0000: ldstr "Hello World"
IL_0005: ret
myString2:
IL_0000: ldstr "Hello World"
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ret
So in a sense the IL would add two more lines but this is a small diffence i think.
Both are valid but using Return
saves having to add Exit Function
if you want to return part way through a function so it is preferable:
If param.length=0 then
Msgbox "Invalid parameter length"
Return Nothing
End If
Compare with:
If param.length=0 then
Msgbox "Invalid parameter length"
Foo = Nothing
Exit Function
End If
Also If you use Return
you don't have to remember to right click Rename to rename all instances of Foo to FooNew if you decide to change the name of your function.
Alongside the other answers, there is also a difference, as follows:
Public Function Test() As Integer
Try
Dim retVal as Integer = 0
retVal = DoSomethingExceptional()
Catch ex as Exception ' bad practice, I know
Finally
Test = retVal
End Try
End Function
You can't put a Return in a Finally block, but you can assign the value of the function there.
精彩评论