Sub Procedures and Functions in VB.net

By: Steven Holzner Emailed: 1757 times Printed: 2444 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

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

VB.net Home | All VB.net Tutorials | Latest VB.net Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(1)


1. View Comment

actually very good site. I learned more & more very well.thank you so much

View Tutorial          By: shiranthi at 2012-07-12 12:18:38

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Steven Holzner
Changes in Controls from VB6 to VB.net
Throwing a Custom Exception in VB.net
Throwing an Exception in VB.net
Using Finally in VB.net
Using Multiple Catch Statements in VB.net
Exception Filtering in the Catch Block in VB.net
Raising an Exception Intentionally in VB.net
Getting an Exception's Number and Description in VB.net
Using On Error GoTo 0 in VB.net
Using Resume Next and Resume Line in VB.net
Understanding Scope in VB.net
Properties in VB.net
Procedure Delegates in VB.net
Preserving a Variable's Values between Procedure Calls in VB.net
Specifying Optional Arguments with default values in Procedures in VB.net

More Tutorials in VB.net
Scope in VB.net
Unstructured Exception Handling in VB.net
Structured Exception Handling in VB.net
Creating Sub Procedures in VB.net
Creating Functions 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
Procedure Delegates in VB.net
Properties in VB.net
Understanding Scope in VB.net
Using Resume Next and Resume Line in VB.net
Using On Error GoTo 0 in VB.net
Getting an Exception's Number and Description in VB.net
Raising an Exception Intentionally in VB.net

More Latest News
Most Viewed Articles (in VB.net )
Your first VB.NET Crystal Reports - A step by step guide
How to export from DataGridView to excel using VB.net
How to export from database to excel using VB.net
Sub Procedures and Functions in VB.net
Insert cell data in an Excel file using OLEDB in VB.net
A tutorial on Chat Server and Chat Client in VB.net
How To Connect To A MySql Database in VB.net
Handling Strings in VB.net
Using Select Case in VB.net
Using Resume Next and Resume Line in VB.net
What's New in VB .NET? A comparison of VB vs VB.net
Operators in VB.net
Handling Dates and Times in VB.net
Handling Timer Events - and Creating an Alarm Clock in VB.net
File Extensions Used in VB .NET
Most Emailed Articles (in VB.net)
ArrayList data structure in VB.net
“Using If with And” and Comparing two integers using If
Nested If and Single line if statement
The Select Case statement in VB.net
The For Loop in VB.net
What's New in VB .NET? A comparison of VB vs VB.net
What is .NET Framework and the Common Language Runtime?
Debug and Release Versions in .NET
File Extensions Used in VB .NET
Assemblies, Solutions and Projects in VB .NET
The Option and Imports Statements in VB .NET
Visual Basic Statements
Data types in VB.net
Converting between Data Types in VB.net
Arrays and Dynamic Arrays in VB.net