Difference Between Using A Function and Method

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 7

Difference between Using a

Function and Method in VB


Defining a Function
A function is a group of reusable code which can be called anywhere in your program.
This eliminate the need of writing the same code again and again, it helps programmers
in writing modular codes. All data that is passed to a function is explicitly passed.
The function statements is used to declare the name, parameter and the body of the
function.
The syntax for the Function statement is:
[Modifiers] Function FunctionName [(Parameter list)] As ReturnType[Statements]
End Function
Where
• Modifiers – specify the access level of the function, possible values are: Public,
Private, Protected etc.
• FunctionName – indicates the name of the function
• ParameterList – specifies the list of the parameter
• ReturnType- specifies the data type the variable the function returns
Public Function functionName
(Argument As datatype,……) As datatype
or
Private Function functionName
(Argument As datatype,……) As datatype
The keyword Public indicates that the function is applicable to the
whole project and the keyword Private indicates that the function is
only applicable to a certain module or procedure. The argument is a
parameter that can pass a value back to the function. There is no limit
to the number of arguments you can put in. The keyword to pass
argument by reference is ByRef and the keyword to pass argument by
value is ByVal.
Using of Method
We use methods(or procedures) for reusing codes and making code
more understandable. A method is just a block of code that you can
call. They are already used methods like WriteLine(), some methods
allow you pass data.
Syntax:
Private sub methodName()
End Sub
Example: (VAT Calculator)
Function VAT(ByVal pCost As Double, ByVal cRate As Double)
cRate= (cRate + 100) /100
Return pCost * cRate
End Function
Function Returning Value
In VB, a function can return a value to the calling code in two ways:
• By using return statements
• By assigning the value to the function name
Note: A function which can call itself is known as Recursive Function
Examples:
Module myFunctions
Function FindMax(ByVal num1 As Integer, ByVal num2 As Integer) As Integer
Dim result As Integer
If (num1 > num2) Then
result = num1
Else
result = num2
End If
FindMax = result
End Function
Program Continuation
Sub Main()
Dim a As Integer = 100
Dim b As Integer = 200
Dim res As Integer
res= FindMax(a, b)
Console. WriteLine(“Max value is :{0} “, res)
Console. ReadLine()
End Sub
End Module
(The result of the above program is “Max value is: 200”)

You might also like