Procedures and Function

  • Code snippets written for a particular process which is to be executed many times from different parts of the program
  • Avoid repetition of the same code in many places for the same purpose
  • Saves time and memory
Defining Procedures Syntax:
Public| Protected |Friend |Protected Friend |Private Sub subname [(argumentlist)]
Statements
End Sub

Example:
Sub MySub (ByVal S1 As String)
System.console.writeline(S1);
End Sub

Return and Exit Sub
  • Exit Sub statement causes an immediate exit from a Sub procedure
  • A Return statement can also be used to immediately exit the procedure
  • Sub SubComputeArea(ByVal Length As Double, ByVal Width As Double)
    Dim Area As Double ' Declare local variable.
    If Length = 0 Or Width = 0 Then
    ' If either argument = 0.
    Exit Sub '           Exit Sub immediately.
    End If
    Area = Length * Width          ' Calculate area of rectangle.
    System.Console.WriteLine(Area)
    ' Print Area to Immediate window.
    End Sub

  • You can also create functions with return values
  • Declaring functions is also much like declaring a Sub procedure, except that you use a keyword Function instead of Sub and specify the return type
  • You return a value from a function with the Return statement
  • You return a value from a function with the Return statement
  • You can also avoid using Return statement if you simply assign value to the name of the function

Note: Parameters to the Functions and Procedures can be passed by Value or by Reference

Preserving a variables value between procedure call
  • The value of a variable can be retained between procedure calls by declaring that variable as static
  • You must explicitly declare all static variables.
Example
Module Module1
Sub Main()
Dim loopIndex As Integer, intValue = 0
For loopIndex = 0 To 3
intValue = Count_on()
System.Console.WriteLine(intValue)
Next loopIndex
End Sub
Function Count_on() As Integer
Static countValue As Integer = 0
countValue += 1
Return countValue
End Function
End Module


Arrays << Previous

Next >> Exception Handling

Our aim is to provide information to the knowledge seekers. 


comments powered by Disqus




Footer1