Sub Procedures and Functions in VB.net
By: Steven Holzner in VB.net Tutorials on 2008-11-25
Procedures are made up of series of Visual Basic statements that, when called, are executed. After the call is finished, control returns to the statement that called the procedure. In this way, procedures make it simple for you to package your code into discrete units. Ideally, each Visual Basic procedure should handle one-and only one-task, to make this easy to remember. You can pass data to procedures and the code in the procedure can work on that data. As mentioned above, there are two types of procedures in Visual Basic .NET: Sub procedures and functions. Sub procedures do not return a value, while functions do.
Let's take a look at creating a Sub procedure first.
Module Module1 Sub Main() System.Console.WriteLine("Hello from Visual Basic") End Sub End Module
When this console application starts, control is transferred to the Main Sub procedure automatically, and the code in it runs. However, we can create our own Sub procedures as well, as below where I'm creating a Sub procedure named DisplayMessage to display the same message the above code does:
Module Module1 Sub Main() End Sub Sub DisplayMessage() System.Console.WriteLine("Hello from Visual Basic") End Sub End Module
To execute the code in DisplayMessage, you must call that Sub procedure, which looks like this:
Module Module1
Sub Main()
DisplayMessage()
End Sub
Sub DisplayMessage()
System.Console.WriteLine("Hello from Visual Basic")
End Sub
End Module
Tip |
Optionally, you also can use the Call statement to call a Sub procedure like this: Call DisplayMessage. Although this usage is considered old-fashioned, it can make your code more readable. |
This produces the same results as before, displaying the message "Hello from Visual Basic"; when you call DisplayMessage, the code in that Sub procedure is executed. Note the parentheses following DisplayMessage above; you use these to enclose data you pass to the procedure, which are called arguments. For example, to pass to DisplayMessage the text string we want to display, you can indicate that it accepts a text-string argument, like this:
Module Module1 Sub Main() End Sub Sub DisplayMessage(ByVal strText As String) ⋮ End Sub End Module
Here, the keyword ByVal indicates that the text string is passed by value, which means a copy of the string is passed. This is the default in VB .NET. The other possibility is ByRef, which means that the argument will be passed by reference. When you pass a variable by reference (which was the default in VB6 and earlier), the location of the variable is passed to the procedure, which means you have direct access to that variable back in the calling code. Changing the value in that variable (as by assigning it a new value like this: intArgument1 = 5) actually changes its value back in the code that called the procedure. In this way, if you pass variables by reference (but not by value) to a procedure, the code in that procedure can change the value in those variables.
Now that I've given the argument passed to DisplayMessage a name (strText), I can refer to that argument by name in the body of DisplayMessage:
Module Module1
Sub Main()
End Sub
Sub DisplayMessage(ByVal strText As String)
System.Console.WriteLine(strText)
End Sub
End Module
And I can pass data to DisplayMessage when I call it (this string, "Hello from Visual Basic", will be stored in strText in DisplayMessage):
Module Module1
Sub Main()
DisplayMessage("Hello from Visual Basic")
End Sub
Sub DisplayMessage(ByVal strText As String)
System.Console.WriteLine(strText)
End Sub
End Module
This code displays our message as before.
Tip |
In VB6 and earlier versions, using parentheses to enclose the arguments you're passing to a procedure was optional under certain circumstances (as when you called Sub procedures). In VB .NET, that's no longer true; you must always use parentheses now, unless you're not passing any arguments to the procedure, in which case you can either use empty parentheses or omit them altogether. |
You can also create functions, which return values. For example, I might create a function named Addem that accepts two integer arguments and returns their sum. Declaring a function is much like declaring a Sub procedure, except that you use the keyword Function instead of Sub, and specify the return type of the function like this (note that you separate multiple arguments in the declaration of a procedure with commas):
Module Module1 Sub Main() End Sub Function Addem(ByVal int1 As Integer, ByVal int2 As Integer) As Long Return int1 + int2 End Function End Module
You return a value from a function with the Return statement, as I have here, where I'm returning the sum of the two arguments passed to us. You also can avoid using the Return statement if you simply assign a value to the name of a function, as in this example, where the Always5 function always returns a value of 5:
Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load MsgBox(Always5()) End Sub Private Function Always5() As Integer Always5 = 5 End Function
Tip |
In Visual Basic 6.0, you could use the Return statement only to branch back to the code following a GoSub statement. In Visual Basic .NET, the GoSub statement is not supported, and you can use the Return statement to return control to the calling program from a Function or Sub procedure. |
When you call a function by using its name and an argument list enclosed in parentheses, that name is replaced by the value returned by the function. For example, the call Addem(2, 2) is replaced by the value 4, as in this code:
Module Module1 Sub Main() Dim intValue As Integer = 2 System.Console.WriteLine("{0}+{1}={2}", _ intValue, intValue, Addem(intValue, intValue)) End Sub Function Addem(ByVal int1 As Integer, ByVal int2 As Integer) As Long Return int1 + int2 End Function End Module
Tip |
Note that I'm using syntax in WriteLine, passing it a text string with terms like{0}, {1}; {0} will be replaced with the first argument following the text string, {1} with the second, and so on. |
When you run this code, you see this result:
2+2=4
Add Comment
This policy contains information about your privacy. By posting, you are declaring that you understand this policy:
- Your name, rating, website address, town, country, state and comment will be publicly displayed if entered.
- Aside from the data entered into these form fields, other stored data about your comment will include:
- Your IP address (not displayed)
- The time/date of your submission (displayed)
- Your email address will not be shared. It is collected for only two reasons:
- Administrative purposes, should a need to contact you arise.
- To inform you of new comments, should you subscribe to receive notifications.
- A cookie may be set on your computer. This is used to remember your inputs. It will expire by itself.
This policy is subject to change at any time and without notice.
These terms and conditions contain rules about posting comments. By submitting a comment, you are declaring that you agree with these rules:
- Although the administrator will attempt to moderate comments, it is impossible for every comment to have been moderated at any given time.
- You acknowledge that all comments express the views and opinions of the original author and not those of the administrator.
- You agree not to post any material which is knowingly false, obscene, hateful, threatening, harassing or invasive of a person's privacy.
- The administrator has the right to edit, move or remove any comment for any reason and without notice.
Failure to comply with these rules may result in being banned from submitting further comments.
These terms and conditions are subject to change at any time and without notice.
- Data Science
- Android
- React Native
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Related Tutorials
Changes in Controls from VB6 to VB.net
Unstructured Exception Handling in VB.net
Structured Exception Handling in VB.net
Creating Sub Procedures in VB.net
Passing a Variable Number of Arguments to Procedures in VB.net
Specifying Optional Arguments with default values in Procedures in VB.net
Preserving a Variable's Values between Procedure Calls in VB.net
Throwing an Exception in VB.net
Comments