Understanding VB.Net Procedures and Functions
Understanding VB.Net Procedures and Functions
PROCEDURES
A procedure is a group of statements that together perform a task when called. After the procedure is
executed, the control returns to the statement calling the procedures.
Types of procedures
They are 2 types of procedures. They are
1. Sub procedure
2. Function procedure
Sub procedure:
It’s performing specific tasks, such as generating an order ID or connecting to a database. Sub
procedures are procedures that do not return any value.
Defining Sub Procedures
The Sub statement is used to declare the name, parameter and the body of a sub procedure.
Syntax :
[Modifiers] Sub SubName [(ParameterList)]
[Statements]
End Sub
Where,
Modifiers − specify the access level of the procedure; possible values are - Public, Private, Protected,
Friend, Protected Friend and information regarding overloading, overriding, sharing, and shadowing.
SubName − indicates the name of the Sub
ParameterList − specifies the list of the parameters
Example
Module mysub
Sub CalculatePay(ByRef hours As Double, ByRef wage As Decimal)
'local variable declaration
Dim pay As Double
pay = hours * wage
[Link]("Total Pay: {0:C}", pay)
End Sub
Sub Main()
'calling the CalculatePay Sub Procedure
CalculatePay(25, 10)
CalculatePay(40, 20)
CalculatePay(30, 27.5)
[Link]()
End Sub
End Module
Passing Parameters by Value
In this mechanism, when a method is called, a new storage location is created for each value
parameter. The values of the actual parameters are copied into them. So, the changes made to the parameter
inside the method have no effect on the argument. In [Link], to declare the reference parameters using
the ByVal keyword
Passing Parameters by Reference
A reference parameter is a reference to a memory location of a variable. When you pass parameters by
reference, unlike value parameters, a new storage location is not created for these parameters. The reference
parameters represent the same memory location as the actual parameters that are supplied to the method. In
[Link], to declare the reference parameters using the ByRef keyword.
The sub main procedure
Its executed first when a visual basic program is run is the main procedures.
1
Syntax:
Sub Main()
-----
End Sub
Functions procedures:
Its perform procedures perform specific tasks and return a value to the calling statement
Defining a Function
The Function statement is used to declare the name, parameter and the body of a function.
syntax
[Modifiers] Function FunctionName [(ParameterList)] As ReturnType
[Statements]
End Function
Modifiers − specify the access level of the function; possible values are: Public, Private, Protected,
Friend, Protected Friend and information regarding overloading, overriding, sharing, and shadowing.
FunctionName − indicates the name of the function
ParameterList − specifies the list of the parameters
ReturnType − specifies the data type of the variable the function returns
Example program
Function FindMax(ByVal num1 As Integer, ByVal num2 As Integer) As Integer
' local variable declaration */
Dim result As Integer
If (num = 1) Then
Return 1
Else
result = factorial(num - 1) * num
Return result
End If
End Function
Sub Main()
2
'calling the factorial method
[Link]("Factorial of 6 is : {0}", factorial(6))
[Link]("Factorial of 7 is : {0}", factorial(7))
[Link]("Factorial of 8 is : {0}", factorial(8))
[Link]()
End Sub
End Module
Param Arrays
At times, while declaring a function or sub procedure, you are not sure of the number of arguments
passed as a parameter.
Passing Arrays as Function Arguments
To can pass an array as a function argument in [Link].
Built in functions
The Date data type contains date values, time values, or date and time values. The default value of
Date is [Link] (midnight) on January 1, 0001. The equivalent .NET data type is [Link].
The DateTime structure represents an instant in time, typically expressed as a date and time of day
'Declaration
<SerializableAttribute> _
Public Structure DateTime _
Implements IComparable, IFormattable, IConvertible, ISerializable,
IComparable(Of DateTime), IEquatable(Of DateTime)
They can also get the current date and time from the DateAndTime class.
The DateAndTime module contains the procedures and properties used in date and time operations.
'Declaration
<StandardModuleAttribute> _
Public NotInheritable Class DateAndTime
Gets a DateTime object that is set to the current date and time on this computer, expressed as the
Coordinated Universal Time (UTC).
The following table lists some of the commonly used methods of the DateTime structure −
[Link] Method Name & Description
3
Public Function AddMonths (months As Integer) As DateTime
5
Returns a new DateTime that adds the specified number of months to the value of this instance.
4
End Module
Output: Today is: 12/11/2012 [Link] AM
Create a DateTime object in one of the following ways −
By calling a DateTime constructor from any of the overloaded DateTime constructors.
By assigning the DateTime object a date and time value returned by a property or method.
By parsing the string representation of a date and time value.
By calling the DateTime structure's implicit default constructor.
Formatting Date
A Date literal should be enclosed within hash signs (# #), and specified in the format M/d/yyyy, for
example #12/16/2012#. Otherwise, your code may change depending on the locale in which your application
is running.
Predefined Date/Time Formats
The following table identifies the predefined date and time format names. These may be used by name
as the style argument for the Format function –
Format Description
Displays a date using your current culture's short date format. For
Short Date, or d
example, 12/12/2012.
Displays the long date and short time according to your current
f culture's format. For example, Sunday, December 16, 2012 12:15
AM.
Displays the long date and long time according to your current
F culture's format. For example, Sunday, December 16, 2012
[Link] AM.
Displays the short date and short time according to your current
g
culture's format. For example, 12/16/2012 12:15 AM.
s Formats the date and time as a sortable index. For example, 2012-
5
12-16T[Link].
Formats the date and time as a GMT sortable index. For example,
u
2012-12-16 [Link]Z.
Formats the date and time with the long date and long time as
U
GMT. For example, Sunday, December 16, 2012 [Link] PM.
Formats the date as the year and month. For example, December,
Y, y
2012.
Date
1
Returns or sets a String value representing the current date according to your system.
Now
2
Returns a Date value containing the current date and time according to your system.
TimeOfDay
3
Returns or sets a Date value containing the current time of day according to your system.
Timer
4
Returns a Double value representing the number of seconds elapsed since midnight.
TimeString
5
Returns or sets a String value representing the current time of day according to your system.
Today
6
Gets the current date.
Dialog Box
A dialog box in [Link] is a graphical user interface component that prompts the user for input,
displays messages, or provides options for the user to make choices. It is commonly used to interact with the
user during program execution.
MessageBox:
The MessageBox class in [Link] allows you to display messages or prompts to the user.
[Link]("Hello, World!")
InputBox:
The InputBox function displays a dialog box that prompts the user for input.
Dim name As String = InputBox("Please enter your name:")
OpenFileDialog:
6
The OpenFileDialog control allows the user to browse and select files from the system.
Dim openFileDialog As New OpenFileDialog()
If [Link]() = [Link] Then
Dim selectedFile As String = [Link]
' Process the selected file
End If
SaveFileDialog:
The SaveFileDialog control allows the user to specify a file name and location to save a file.
Dim saveFileDialog As New SaveFileDialog()
If [Link]() = [Link] Then
Dim savePath As String = [Link]
' Save the file to the specified location
End If
ColorDialog:
The ColorDialog control allows the user to select a color.
Dim colorDialog As New ColorDialog()
If [Link]() = [Link] Then
Dim selectedColor As Color = [Link]
' Use the selected color
End If
FontDialog:
The FontDialog control allows the user to select a font.
Dim fontDialog As New FontDialog()
If [Link]() = [Link] Then
Dim selectedFont As Font = [Link]
' Use the selected font
End If
FolderBrowserDialog:
The FolderBrowserDialog control allows the user to browse and select a folder.
Dim folderBrowserDialog As New FolderBrowserDialog()
If [Link]() = [Link] Then
Dim selectedFolder As String = [Link]
' Process the selected folder
End If
The common dialog boxes
Dialog boxes provide a convenient way to interact with users, gather input, and display information.
By using these dialog boxes, to enhance the user experience and make your application more interactive and
user-friendly.
PrintDialog:
The PrintDialog control allows the user to select a printer and configure print settings.
Dim printDialog As New PrintDialog()
If [Link]() = [Link] Then
' Perform printing operation using the selected printer and settings
End If
7
PageSetupDialog:
The PageSetupDialog control allows the user to configure page setup settings for printing.
Dim pageSetupDialog As New PageSetupDialog()
If [Link]() = [Link] Then
' Retrieve and use the selected page setup settings
End If
The FileMode enumerator defines various methods for opening files. The members
of the FileMode enumerator are −
Append − It opens an existing file and puts cursor at the end of file, or
creates the file, if the file does not exist.
Create − It creates a new file.
FileMode CreateNew − It specifies to the operating system that it should create a new
file.
Open − It opens an existing file.
OpenOrCreate − It specifies to the operating system that it should open a
file if it exists, otherwise it should create a new file.
Truncate − It opens an existing file and truncates its size to zero bytes.
9
Write − It allows opening the file for writing
Advanced File Operations in [Link]
The immense powers of [Link] classes, you need to know the commonly used properties and
methods of these classes.
Error handling
There are several types of errors or exceptions that can occur
Exception Handling
An exception is an unwanted error that occurs during the execution of a program and can be a system
exception or application exception. Exceptions are nothing but some abnormal and typically an event or
condition that arises during the execution, which may interrupt the normal flow of the program.
An exception can occur due to different reasons, including the following:
o A user has entered incorrect data or performs a division operator, such as an attempt to divide by zero.
o A connection has been lost in the middle of communication, or system memory has run out.
o A user has entered incorrect data or performs a division operator, such as an attempt to divide by zero.
o A connection has been lost in the middle of communication, or system memory has run out.
Exception Handling
When an error occurred during the execution of a program, the exception provides a way to transfer
control from one part of the program to another using exception handling to handle the
error. [Link] exception has four built-in keywords such as Try, Catch, Finally, and Throw to handle and
move controls from one part of the program to another.
Keywor Description
d
Try A try block is used to monitor a particular exception that may throw an exception within
the application. And to handle these exceptions, it always follows one or more catch
blocks.
Catch It is a block of code that catches an exception with an exception handler at the place in a
program where the problem arises.
Finally It is used to execute a set of statements in a program, whether an exception has occurred.
Throw As the name suggests, a throw handler is used to throw an exception after the occurrence
10
of a problem.
Syntax for Try/Catch
Assuming a block will raise an exception, a method catches an exception using a combination of the
Try and Catch keywords. A Try/Catch block is placed around the code that might generate an exception. Code
within a Try/Catch block is referred to as protected code, and the syntax for using Try/Catch looks like the
following
Try
[ tryStatements ]
[ Exit Try ]
[ Catch [ exception [ As type ] ] [ When expression ]
[ catchStatements ]
[ Exit Try ] ]
[ Catch ... ]
[ Finally
[ finallyStatements ] ]
End Try
Exception Classes
In [Link], there are various types of exceptions represented by classes. And these exception classes
originate from their parent's class '[Link]'.
The following are the two exception classes used primarily in [Link].
1. [Link]
2. [Link]
[Link]:
It is a base class that includes all predefined exception classes, and some system-generated exception
classes that have been generated during a run time such as DivideByZeroException,
IndexOutOfRangeException, StackOverflowExpression, and so on.
[Link]:
It is an exception class that throws an exception defined within the application by the programmer or
developer. Furthermore, we can say that it is a user-defined exception that inherits
from [Link] class.
Syntax of exception handler block
Try
' code or statement to be executed
[ Exit Try block]
' catch statement followed by Try block
Catch [ Exception name] As [ Exception Type]
[Catch1 Statements] Catch [Exception name] As [Exception Type]
[ Exit Try ]
[ Finally
[ Finally Statements ] ]
End Try
Creating User-Defined Exceptions
To define your own exception. User-defined exception classes are derived from
the ApplicationException class.
Throwing Objects
In [Link] exception handling, we can throw an object exception directly or indirectly derived from
the [Link] class. To throw an object using the throw statement in a catch block, such as:
11
Throw [ expression ]
Namespace
As programming languages have evolved, the frameworks around them have greatly increased in size.
The .NET framework provides a huge number of base classes, data types, algorithms, etc.
Declaring a Namespace
Namespaces are declared using the namespace keyword. The basic syntax for creating a namespace is
very simple, requiring only a name for the new grouping and a code block surrounded by braces:
Syntax:
namespace namespace-name {}
namespace FirstNamespace
{
class Test
{
public void ShowMessage()
{
[Link]("This is the first namespace!");
}
}
}
This code creates a new namespace named "FirstNamespace" and defines a "Test" class containing a
single method that outputs a string to the console
namespace SecondNamespace
{
class Test
{
public void ShowMessage()
{
[Link]("This is the second namespace!");
}
}
}
using FirstNamespace;
12
Nested Namespaces
How classes and other items can be declared within a namespace to provide grouping of code items
and isolation of names to prevent conflicts.
namespace Parent
{
namespace Child
{
namespace Grandchild
{
class Test
{
public void ShowMessage()
{
[Link]("This is a nested namespace!");
}}
}
}
}
Class Definition
A class definition starts with the keyword Class followed by the class name; and the class body, ended
by the End Class statement. Following is the general form of a class definition.
[ <attributelist> ] [ accessmodifier ] [ Shadows ] [ MustInherit | NotInheritable ] [ Partial ] _
Class name [ ( Of typelist ) ]
[ Inherits classname ]
[ Implements interfacenames ]
[ statements ]
End Class
Where,
attributelist is a list of attributes that apply to the class. Optional.
accessmodifier defines the access levels of the class, it has values as - Public, Protected, Friend,
Protected Friend and Private. Optional.
Shadows indicate that the variable re-declares and hides an identically named element, or set of
overloaded elements, in a base class. Optional.
MustInherit specifies that the class can be used only as a base class and that you cannot create an
object directly from it, i.e., an abstract class. Optional.
NotInheritable specifies that the class cannot be used as a base class.
Partial indicates a partial definition of the class.
Inherits specifies the base class it is inheriting from.
Implements specifies the interfaces the class is inheriting from.
The Syntax for creating an object
Dim Obj_Name As Class_Name = New Class_Name() ' Declaration of object
Obj_Name.Method_Name() ' Access a method using the object
Member Function
The member function of a class is used to define the structure of member inside the definition of the
class. It can be accessed by all defined objects of the class and operated on the data member. Furthermore,
member variables are the attributes of an object to be implemented to a member function. And we can access
member variables using the public member function.
Constructor and Destructor
The constructor is a special method that is implemented when an object of a particular class is created.
Constructor is also useful for creating and setting default values for a new object of a data member.
13
To create a class without defining a constructor, the compiler automatically creates a default
constructor. In this way, there is a constructor that is always available in every class. Furthermore, we can
create more than one constructor in a class with the use of New keyword but with the different parameters,
and it does not return anything.
Default Constructor: to create a constructor without defining an argument, it is called a default
constructor.
Syntax
Public Class MyClass
' Creates a Constructor using the New
Public Sub New()
'Statement to be executed
End Sub
End Class
Parameterized Constructor
To pass one or more arguments to a constructor, the constructor is known as a parameterized
constructor. And the object of the class should be initialized with arguments when it is created.
Destructor
Destructor is a special function that is used to destroy a class object when the object of the class goes
out of scope. It can be represented as the Finalize() method and does not accept any parameter nor return any
value. Furthermore, it can be called automatically when a class object is not needed.
Destructor Syntax
Destructor using the Finalize() method in [Link].
Class My_Destructor
' define the destructor
Protected Overrides Sub Finalize()
' Statement or code to be executed
End Sub
End Class
Multithreading
Thread
When two or more processes execute simultaneously in a program, the process is known as
multithreading. And the execution of each process is known as the thread. A single thread is used to execute
a single logic or task in an application. By default, each application has one or more threads to execute each
process, and that thread is known as the main thread.
To create and access a new thread in the Thread class, we need to import
the [Link] namespace. When the execution of a program begins in [Link], the Main thread is
automatically called to handle the program logic. And if we create another thread to execute the process in
Thread class, the new thread will become the child thread for the main thread.
Create a new Thread
To create a thread by extending the Thread class and pass the ThreadStart delegate as an argument to
the Thread constructor. A ThreadStart() is a method executed by the new thread. We need to call
the Start() method to start the execution of the new thread because it is initially in the unstart state. And the
PrintInfo parameter contains an executable statement that is executed when creating a new thread
Create a new thread
Dim th As Thread = New Thread( New ThreadStart(PrintInfo)
' Start the execution of newly thread
[Link]()
Thread Methods
The following are the most commonly used methods of Thread class.
14
Method Description
Equals() It is used to check whether the current and defined thread object are equal.
Interrupt() It is used to interrupt a thread from the Wait, sleep, and join thread state.
Join() It is a synchronization method that stops the calling thread until the
execution thread completes.
Resume() As the name suggests, a Resume() method is used to resume a thread that
has been suspended.
Sleep() It is used to suspend the currently executing thread for a specified time.
Start() It is used to start the execution of thread or change the state of an ongoing
instance.
State Description
Runnable When we call a Start() method to prepare a thread for running, the runnable situation
occurs.
Not It indicates that the thread is not in a runnable state, which means that the thread in
Runnable sleep() or wait() or suspend() or is blocked by the I/O operation.
Dead If the thread is in a dead state, either the thread has been completed its work or aborted
Multithreading
When two or more processes are executed in a program to simultaneously perform multiple tasks, the
process is known as multithreading. To execute an application, the Main thread will automatically be called
to execute the programming logic synchronously, which means it executes one process after another. In this
way, the second process has to wait until the first process is completed, and it takes time
15
Message Queuing (MSMQ)
Message Queuing (MSMQ) technology enables applications running at different times to
communicate across heterogeneous networks and systems that may be temporarily offline. Applications send
messages to queues and read messages from queues. The following illustration shows how a queue can hold
messages that are generated by multiple sending applications and read by multiple receiving applications.
It can be used to implement solutions to both asynchronous and synchronous scenarios requiring high
performance. The following list shows several places where Message Queuing can be used.
Mission-critical financial services: for example, electronic commerce.
Embedded and hand-held applications: for example, underlying communications to and from embedded
devices that route baggage through airports by means of an automatic baggage system.
Outside sales: for example, sales automation applications for traveling sales representatives.
Workflow: Message Queuing makes it easy to create a workflow that updates each system. A typical
design pattern is to implement an agent to interact with each system. Using a workflow-agent
architecture also minimizes the impact of changes in one system on the other systems. With Message
Queuing, the loose coupling between systems makes upgrading individual systems simpler.
Programming MSMQ
The concepts of MSMQ programming like creating a queue, writing a message to the queue and receiving
from it etc.
16
Enter [Link]
To build a messaging application we need to create a queue first, have one application send messages
to it and have another application receive those messages from it.
The basic types of MSMQ queues: Private and Public. Public queues are those that are published in
the active directory. So, applications running on different servers throughout the network can find and
use public queues through the active directory. Private queues on the other hand are available locally on a
particular machine and are not published in the active directory.
The [Link] namespace provides a set of classes which can be used to work with MSMQ.
The MessageQueue class provides all the necessary functionality to work with and manipulate MSMQ
queues. It is like a wrapper around message queuing. The Message class provides everything required to
define and use an MSMQ message.
Creating a Queue
Queues can be created either programmatically or through the computer management snap-in. I
presume MSMQ is installed on your system.
Programmatically
The Create shared method of the MessageQueue class to create a queue. In the code snippet given
below I am creating a private queue named MyNewQueue.
Try
Dim queueAsMessageQueue
queue = [Link](".\Private$\MyNewQueue")
' If there is an error creating a queue you get a MessageQueueException exception
Catch ex As MessageQueueException
End Try
Note the parameter I have passed to the the Create method. It is called the path of the queue. The single dot (.)
in the path indicates the queue is created on the local machine. Since we are creating a private queue here, we
need to include a Private$ in the path. If we are creating or accessing a public queue we can just use
the MachineName\QueueName format in the path.
Through the computer management snap-in
1. Open the computer management snap-in.
2. Navigate to the [Message Queuing] node under the Services and Applications section.
3. Right click on the [Private Queues] and in the context menu that appears select New -> Private Queue. Public
queues can be created in a similar fashion
17
Sending a simple message
The Send method of the MessageQueue object to post a message to the queue.
[Link]("<<Message>>", "<<Message Label>>")
This can be a Message object or any managed object. If the object is not of type Message, then the object is
serialized and stored in the message body.
Reading a message from the queue
There are two types of operations with respect to reading a message from the Queue: Peeking and
Receiving.
1. Receive a message from the queue, the message is removed from the queue.
2. Peeking is similar to Receiving but here the message is not removed from the queue.
Dim msg As Message
msg = [Link]()
[Link]([Link])
There are many overloads of Receive and the one used above indefinitely blocks the caller till
a message is available on the queue. To do not want to get blocked indefinitely.
The overload of Receive which takes a TimeSpan argument and this throws an exception if a message
is not received within that time span. Here is a call to receive which times out after 1000 ticks (1 second).
msg = [Link](New TimeSpan(1000))
Peek and Receive operations are synchronous in nature. However there exists a method where we can do
these operations asynchronously.
The BeginPeek and EndPeek or BeginReceive or EndReceive respectively.
Deleting a Queue
The Delete shared method of the MessageQueue object to delete a queue from the system.
18
[Link](".\Private$\MyNewQueue")
[Link](".\Private$\MyNewQueue")
19