|
Methods
A Method is a procedure built into the class. They are a series of statements
that are executed when called. Methods allow us to handle code in a simple
and organized fashion. There are two types of methods in VB .NET: those that return
a value (Functions) and those that do not return a value (Sub Procedures). Both of
them are discussed below.
Sub Procedures
Sub procedures are methods which do not return
a value. Each time when the Sub procedure is called the statements within it are executed
until the matching End Sub is encountered. Sub Main(), the starting point
of the program itself is a sub procedure. When the application starts execution, control
is transferred to Main Sub procedure automatically which
is called by default.
Example of a Sub Procedure
Module Module1
Sub Main()
'sub procedure Main() is called by default
Display()
'sub procedure display() which we are creating
End Sub
Sub Display()
System.Console.WriteLine("Using Sub Procedures")
'executing sub procedure Display()
End Sub
End Module
|
The image below displays output from above code.
Functions
Function is a method which returns a value. Functions are used to evaluate data, make
calculations or to transform data. Declaring a Function is similar to declaring a
Sub procedure. Functions are declared with the Function keyword.
The following code is an example on Functions:
Imports System.Console
Module Module1
Sub Main()
Write("Sum is" & " " & Add())
'calling the function
End Sub
Public Function Add() As Integer
'declaring a function add
Dim i, j As Integer
'declaring two integers and assigning values to them
i = 10
j = 20
Return (i + j)
'performing the sum of two integers and returning it's value
End Function
End Module
|
The image below displays output from above code.
Calling Methods
A method is not executed until it is called. A method is called by referencing it's
name along with any required parameters. For example, the above code called the
Add method in Sub main like this:
Write("Sum is" & " " & Add()).
Method Variables
Variables declared within methods are called method variables. They have method scope
which means that once the method is executed they are destroyed and their memory is
reclaimed. For example, from the above code (Functions) the Add method declared two
integer variables i, j. Those two variables are accessible only within the method
and not from outside the method.
Parameters
A parameter is an argument that is passed to the method by the method that calls it.
Parameters are enclosed in parentheses after the method name in the method declaration.
You must specify types for these parameters. The general form of a method with parameters
looks like this:
Public Function Add(ByVal x1 as Integer, ByVal y1 as Integer)
------------
Implementation
------------
End Function
|