Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax: "Exit Sub" or "Return" in VB.NET subroutines

Both "Exit Sub" or "Return" seem to accomplish the same thing -- exit a subroutine. Is there any difference in how they work under the covers?

That is,

Private Sub exitNow()     Exit Sub End Sub 

or

Private Sub exitNow()     Return End Sub 
like image 829
Jeff Avatar asked Jun 17 '09 01:06

Jeff


People also ask

How do you exit a function in Visual Basic?

In visual basic, we can exit or terminate the execution of the do-while loop immediately by using Exit keyword. Following is the example of using Exit keyword in a do-while loop to terminate loop execution in a visual basic programming language.

How do you create a subroutine in Visual Basic?

Creating a subroutine involves two lines of code. Luckily though, the Visual Basic code editor is smart, and will insert the second line for you! A subroutine begins with the word "Sub", followed by a space, then a name identifying the subroutine. Two parentheses follow, which are used for a parameter list.


2 Answers

From the doc:

In a Sub or Set procedure, the Return statement is equivalent to an Exit Sub or Exit Property statement, and expression must not be supplied.

So they're the same in this context.

(Return (<value>) is used in functions and property.get's. Obviously slightly different in that context).

like image 186
RBarryYoung Avatar answered Sep 22 '22 17:09

RBarryYoung


I tend to prefer Return over Exit Sub. Because once in a while you change from Sub to Function. In this case Exit Sub could be converted to Exit Function, but this assumes that there was a previous assignment to the function name (alike VB 6), which most probably didn't happen. Return would catch this situation - if the method should return a value, Return with no argument will fail at compile time.

like image 30
Mike Avatar answered Sep 21 '22 17:09

Mike