Procedures and Functions in VB.NET
Procedures and functions are the two fundamental constructs in VB.NET programming. In this page, we will discuss the syntax, example, output, explanation, use, important points, and summary of procedures and functions in VB.NET.
Syntax
Procedures and functions are declared using the following syntax:
Function/ Sub FunctionName(Parameters) As ReturnType
'Code Body
End Function/ Sub
Function
is used when a value is returned from the function.Sub
is used when the function doesn't return any value.FunctionName
is the name of the function or procedure.Parameters
is the list of parameters (optional).ReturnType
is the data type returned by the function (required for functions).
Example
Here's an example of a function and a procedure in VB.NET:
' Function to add two numbers
Function Add(ByVal x As Integer, ByVal y As Integer) As Integer
Return x + y
End Function
' Procedure to display a message
Sub DisplayMessage(ByVal msg As String)
Console.WriteLine(msg)
End Sub
' Main method
Sub Main()
Dim sum As Integer = Add(10, 20)
DisplayMessage("Sum of 10 and 20 is " & sum)
End Sub
Output
The output of the program will be:
Sum of 10 and 20 is 30
Explanation
In the above example, we have defined a function called Add
that takes two integer parameters and returns their sum. We have also defined a procedure called DisplayMessage
that takes a string parameter and displays it on the console.
In the Main
method, we call the Add
function to calculate the sum of two numbers and store the result in a variable called sum
. We then call the DisplayMessage
procedure to display the result on the console.
Use
Procedures and functions are used to encapsulate a block of code that can be reused throughout the program. Functions are used to return values, while procedures are used to perform an action without returning any value.
Important Points
- Functions and procedures are declared using the
Function
andSub
keywords, respectively. - A function must specify a return type, while a procedure doesn't.
- Both functions and procedures can take parameters.
Summary
In this page, we discussed the syntax, example, output, explanation, use, important points, and summary of procedures and functions in VB.NET. Procedures and functions are essential constructs in VB.NET programming that allow for code reuse and organization. By using functions and procedures, you can write better-structured code that is easier to maintain and debug.