Visual Basic (VB.NET) Procedures and Functions

In creating a modular program using Visual Basic.Net we always used Procedures and Functions. A procedure and function is a piece of code in larger program. They perform a specific task. Reducing duplication of code, Decomposing complex problems into simpler pieces, Improving of code, Reuse of code, and Information hiding are the common advantage of using procedures and functions.

Procedures

A procedure does not return any value and the statements is enclosed inside the Sub and End Sub. Example:
  1. Public Class testsub
  2.  
  3.     Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
  4.        
  5.  Dim email As String
  6.         'Get the value from textbox named txteamil
  7.         'and stored to string variable email
  8.         email = Txtemail.Text
  9.         'call the sub procedure named checkemel
  10.         Call checkemel(email)
  11.     End Sub
  12.  
  13.     'this is our Procedure
  14.     Sub checkemel(ByVal email As String)
  15.         'test if the user dont e something on the textbox
  16.         If email = "" Then
  17.             'if true then it will ask the user to write the email address
  18.             MsgBox("Please Provide correct email address!")
  19.         Else
  20.             'else it simply display the value inputed by the user
  21.             MsgBox("Your email address is!" & email)
  22.         End If
  23.     End Sub
  24.  
  25. End Class
Output

Functions

A function does something returns a value and using Visual Basic the statements inside Function, End Function. Example:
  1. Public Class testFunctions
  2.  
  3.     Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Click
  4.         Dim first As Integer
  5.         Dim second As Integer
  6.         Dim result As Integer
  7.  
  8.         'assign values to specified variables
  9.         first = Val(num1.Text)
  10.         second = Val(num2.Text)
  11.  
  12.         'calls the function to perform addition
  13.         result = AddTwoNumbers(first, second)
  14.  
  15.  
  16.  
  17.         If result = 0 Then
  18.             MsgBox("Please try again ")
  19.         Else
  20.             MsgBox("The answer is " & result)
  21.         End If
  22.  
  23.     End Sub
  24.  
  25.     Function AddTwoNumbers(ByVal firsts As Integer, ByVal seconds As Integer) As Integer
  26.  
  27.         Dim answer As Integer
  28.  
  29.         answer = firsts + seconds
  30.  
  31.         'AddTwoNumbers = answer
  32.         Return answer
  33.  
  34.     End Function
  35. End Class
Output

Comments

THIS THING IT IS HELPFUL I WOULD LIKE TO STUDY HERE THIS THING MAKE ME UNDERSTAND FUCTION AND FUNCTION PLEASE LIKE TO STUDY HERE .

Add new comment