What is the difference between Return and Exit?
-
Thursday, June 09, 2011 8:19 PMIs there any difference between Exit and Return?
Karl~
All Replies
-
Thursday, June 09, 2011 8:28 PM
Is there any difference between Exit and Return?
Karl~
Hello Karl Fetterhoff
the return statement in a code statement returns a value ends a variable inside a function, see example belowhttp://msdn.microsoft.com/en-us/library/2e34641s.aspx
the exit statement when paired instead ends ona sub ExitSub example, a function ExitFunction or exit from a loop iteration, and more, see the following link
http://msdn.microsoft.com/en-us/library/t2at9t47.aspx
Hello
Carmelo La Monica http://community.visual-basic.it/carmelolamonica/
- Proposed As Answer by John Anthony Oliver Thursday, June 09, 2011 10:17 PM
-
Thursday, June 09, 2011 8:29 PM
Return is for functions and returns what ever the function was supposed to return like
Function GetName() As String Return "Sam" End Function
Exit bails out with out returning any vaule and used in Subs, Loops and what not like
Sub DoSomething(ByVal WithWhat As String) If String.IsNullOrEmpty(WithWhat) Then 'bails out of sub Exit Sub End If Select Case WithWhat Case "Car" For Each Model In Cars If Model.Name = "Jalopie" Then 'bails out of for each loop Exit For End If Next Case "Bike" 'would bail out of the select statement Exit Select Case "Cart" End Select End Sub
- Proposed As Answer by John Anthony Oliver Thursday, June 09, 2011 10:16 PM
-
Thursday, June 09, 2011 8:29 PM
Return sets the object value of the Method before leaping to the end of a Method scope. It only affects Methods.
Exit leaps to the end of the current scope immediately; you can Exit Do, Exit For, Exit Sub, etc etc. This does NOT set the object value of the Method.
If you Return from inside a Do or For, the whole Method is done and the Method's value will be whatever follows the Return keyword.
It never hurts to try. In a worst case scenario, you'll learn from it.- Proposed As Answer by John Anthony Oliver Thursday, June 09, 2011 10:46 PM
- Marked As Answer by Karl Fetterhoff Thursday, June 09, 2011 11:07 PM
-
Thursday, June 09, 2011 9:37 PM
"Exit Sub" and "Return" are identical when used in 'sub' methods.
"Exit Function" is identical to "Return <some value>", except that the value returned is either the last value assigned to the function name or the function type default value if no value was assigned to the function name. The "Exit Function" form is outdated and confusing to people without a background in VB.
Convert between VB, C#, C++, & Java (http://www.tangiblesoftwaresolutions.com) -
Thursday, June 09, 2011 11:14 PMThanks Andrew for clearing that up for me. I figured there was a subtle difference. Your explanation is most helpful. I was never really sure about the consequences of executing a Return while inside a Loop. Nice to know I'm not the only one sweating the details. :)
Karl~

