Thursday, 23 May 2013

VB.net

Want to learn Advanced VB.net click here
VB.Net Programming Tutorial
VB.Net is a simple, modern, object-oriented computer programming language developed by Microsoft to combine the power of the .NET Framework and the common language runtime with the productivity benefits that are the hallmark of Visual Basic.
This tutorial will teach you basic VB.Net programming and will also take you through various advance concepts related to VB.Net programming language.

VB.Net - Overview

Visual Basic .NET (VB.NET) is an object-oriented computer programming language implemented on the .NET Framework. Although it is an evolution of classic Visual Basic language, it is not backwards-compatible with VB6, and any code written in the old version does not compile under VB.NET.
Like all other .NET languages, VB.NET has complete support for object-oriented concepts. Everything in VB.NET is an object, including all of the primitive types (Short, Integer, Long, String, Boolean, etc.) and user defined types, events, and even assemblies. All objects inherits from the base class Object.
VB.NET is implemented of Microsoft's .NET framework. Therefore it has full access all the libraries in the .Net Framework. It's also possible to run VB.NET programs on Mono, the open-source alternative to .NET, not only under Windows, but even Linux or Mac OSX.
The following reasons make VB.Net a widely used professional language:
  • Modern, general purpose.
  • Object oriented.
  • Component oriented.
  • Easy to learn.
  • Structured language.
  • It produces efficient programs.
  • It can be compiled on a variety of computer platforms.
  • Part of .Net Framework.

Strong Programming Features VB.Net

VB.Net has numerous strong programming features that make it endearing to multitude of programmers worldwide. Let us mention some of these features:
  • Boolean Conditions
  • Automatic Garbage Collection
  • Standard Library
  • Assembly Versioning
  • Properties and Events
  • Delegates and Events Management
  • Easy to use Generics
  • Indexers
  • Conditional Compilation
  • Simple Multithreading

VB.Net - Overview

Visual Basic .NET (VB.NET) is an object-oriented computer programming language implemented on the .NET Framework. Although it is an evolution of classic Visual Basic language, it is not backwards-compatible with VB6, and any code written in the old version does not compile under VB.NET.
Like all other .NET languages, VB.NET has complete support for object-oriented concepts. Everything in VB.NET is an object, including all of the primitive types (Short, Integer, Long, String, Boolean, etc.) and user defined types, events, and even assemblies. All objects inherits from the base class Object.
VB.NET is implemented of Microsoft's .NET framework. Therefore it has full access all the libraries in the .Net Framework. It's also possible to run VB.NET programs on Mono, the open-source alternative to .NET, not only under Windows, but even Linux or Mac OSX.
The following reasons make VB.Net a widely used professional language:
  • Modern, general purpose.
  • Object oriented.
  • Component oriented.
  • Easy to learn.
  • Structured language.
  • It produces efficient programs.
  • It can be compiled on a variety of computer platforms.
  • Part of .Net Framework.

Strong Programming Features VB.Net

VB.Net has numerous strong programming features that make it endearing to multitude of programmers worldwide. Let us mention some of these features:
  • Boolean Conditions
  • Automatic Garbage Collection
  • Standard Library
  • Assembly Versioning
  • Properties and Events
  • Delegates and Events Management
  • Easy to use Generics
  • Indexers
  • Conditional Compilation
  • Simple Multithreading

VB.Net - Environment

In this chapter, we will discuss the tools available for creating VB.Net applications.
We have already mentioned that VB.Net is part of .Net framework and used for writing .Net applications. Therefor before discussing the available tools for running a VB.Net program, let us understand how VB.Net relates to the .Net framework.

The .Net Framework

The .Net framework is a revolutionary platform that helps you to write the following types of applications:
  • Windows applications
  • Web applications
  • Web services
The .Net framework applications are multi-platform applications. The framework has been designed in such a way that it can be used from any of the following languages: Visual Basic, C#, C++, Jscript, and COBOL etc.
All these languages can access the framework as well as communicate with each other.
The .Net framework consists of an enormous library of codes used by the client languages like VB.Net. These languages use object oriented methodology.
Following are some of the components of the .Net framework:
  • Common Language Runtime (CLR)
  • The .Net Framework Class Library
  • Common Language Specification
  • Common Type System
  • Metadata and Assemblies
  • Windows Forms
  • ASP.Net and ASP.Net AJAX
  • ADO.Net
  • Windows Workflow Foundation (WF)
  • Windows Presentation Foundation
  • Windows Communication Foundation (WCF)
  • LINQ
For the jobs each of these components perform, please see ASP.Net - Introduction and for details of each component, please consult Microsoft's documentation.

Integrated Development Environment (IDE) For VB.Net

Microsoft provides the following development tools for VB.Net programming:
  • Visual Studio 2010 (VS)
  • Visual Basic 2010 Express (VBE)
  • Visual Web Developer
The last two are free. Using these tools you can write all kinds of VB.Net programs from simple command-line applications to more complex applications. Visual Basic Express and Visual Web Developer Express edition are trimmed down versions of Visual Studio and has the same look and feel. They retain most features of Visual Studio. In this tutorial, we have used Visual Basic 2010 Express and Visual Web Developer (for the web programming chapter).
You can download it from here. It gets automatically installed in your machine. Please note that you need an active internet connection for installing the express edition.

Writing VB.Net Programs on Linux or Mac OS

Although the.NET Framework runs on the Windows operating system, there are some alternative versions that work on other operating systems. Mono is an open-source version of the .NET Framework, which includes a Visual Basic compiler and runs on several operating systems, including various flavors of Linux and Mac OS. The most recent version is VB 2012.
The stated purpose of Mono is not only to be able to run Microsoft .NET applications cross-platform, but also to bring better development tools to Linux developers. Mono can be run on many operating systems including Android, BSD, iOS, Linux, OS X, Windows, Solaris and UNIX.

VB.Net - Program Structure

Before we study basic building blocks of the VB.Net programming language, let us look a bare minimum VB.Net program structure so that we can take it as a reference in upcoming chapters.

VB.Net Hello World Example

A VB.Net program basically consists of the following parts:
  • Namespace declaration
  • A class or module
  • One or more procedures
  • Variables
  • The Main procedure
  • Statements & Expressions
  • Comments
Let us look at a simple code that would print the words "Hello World":
Imports System
Module Module1
   'This program will display Hello World 
   Sub Main()
      Console.WriteLine("Hello World")
      Console.ReadKey()
   End Sub
End Module
When the above code is compiled and executed, it produces following result:
Hello, World!
Let us look various parts of the above program:
  • The first line of the program Imports System is used to include the System namespace in the program.
  • The next line has a Module declaration, the module Module1. VB.Net is completely object oriented, so every program must contain a module of a class that contains the data and procedures that your program uses.
  • Classes or Modules generally would contain more than one procedure. Procedures contain the executable code, or in other words, they define the behavior of the class. A procedure could be any of the following:
    • Function
    • Sub
    • Operator
    • Get
    • Set
    • AddHandler
    • RemoveHandler
    • RaiseEvent
  • The next line( 'This program) will be ignored by the compiler and it has been put to add additional comments in the program.
  • The next line defines the Main procedure, which is the entry point for all VB.Net programs. The Main procedure states what the module or class will do when executed.
  • The Main procedure specifies its behavior with the statement
    Console.WriteLine("Hello World")
    WriteLine is a method of the Console class defined in the System namespace. This statement causes the message "Hello, World!" to be displayed on the screen.
  • The last line Console.ReadKey() is for the VS.NET Users. This will prevent the screen from running and closing quickly when the program is launched from Visual Studio .NET.

Compile & Execute VB.Net Program:

If you are using Visual Studio.Net IDE, take the following steps:
  • Start Visual Studio.
  • On the menu bar, choose File, New, Project.
  • Choose Visual Basic from templates
  • Choose Console Application.
  • Specify a name and location for your project using the Browse button, and then choose the OK button.
  • The new project appears in Solution Explorer.
  • Write code in the Code Editor.
  • Click the Run button or the F5 key to run the project. A Command Prompt window appears that contains the line Hello World.
You can compile a VB.Net program by using the command line instead of the Visual Studio IDE:
  • Open a text editor and add the above mentioned code.
  • Save the file as helloworld.vb
  • Open the command prompt tool and go to the directory where you saved the file.
  • Type vbc helloworld.vb and press enter to compile your code.
  • If there are no errors in your code the command prompt will take you to the next line and would generate helloworld.exe executable file.
  • Next, type helloworld to execute your program.
  • You will be able to see "Hello World" printed on the screen.


VB.Net - Basic Syntax

VB.Net is an object oriented programming language. In Object Oriented Programming methodology a program consists of various objects that interact with each other by means of actions. The actions that an object may take are called methods. Objects of the same kind are said to have the same type or, more often, are said to be in the same class.
When we consider a VB.Net program it can be defined as a collection of objects that communicate via invoking each other's methods. Let us now briefly look into what do class, object, methods and instant variables mean.
  • Object - Objects have states and behaviors. Example: A dog has states-color, name, breed as well as behaviors -wagging, barking, eating etc. An object is an instance of a class.
  • Class - A class can be defined as a template/ blue print that describe the behaviors/states that object of its type support.
  • Methods - A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed.
  • Instant Variables - Each object has its unique set of instant variables. An object's state is created by the values assigned to these instant variables.

A Rectangle Class in VB.Net

For example, let us consider a Rectangle object. It has attributes like length and width. Depending upon the design, it may need ways for accepting the values of these attributes, calculating area and display details.
Let us look at an implementation of a Rectangle class and discuss VB.Net basic syntax, on the basis of our observations in it:
Imports System
Public Class Rectangle
    Private length As Double
    Private width As Double

    'Public methods
    Public Sub AcceptDetails()
        length = 4.5
        width = 3.5
    End Sub

    Public Function GetArea() As Double
        GetArea = length * width
    End Function
    Public Sub Display()
        Console.WriteLine("Length: {0}", length)
        Console.WriteLine("Width: {0}", width)
        Console.WriteLine("Area: {0}", GetArea())

    End Sub

    Shared Sub Main()
        Dim r As New Rectangle()
        r.Acceptdetails()
        r.Display()
        Console.ReadLine()
    End Sub
End Class
When the above code is compiled and executed, it produces following result:
Length: 4.5
Width: 3.5
Area: 15.75
In previous chapter, we created a Visual Basic module that held the code. Sub Main indicates the entry point of VB.Net program. Here, we are using Class that contains both code and data. You use classes to create objects. For example, in the code, r is a Rectangle object.
An object is an instance of a class:
Dim r As New Rectangle()
A class may have members that can be accessible from outside class, if so specified. Data members are called fields and procedure members are called methods.
Shared methods or static methods can be invoked without creating an object of the class. Instance methods are invoked through an object of the class:
Shared Sub Main()
   Dim r As New Rectangle()
   r.Acceptdetails()
   r.Display()
   Console.ReadLine()
End Sub

Identifiers

An identifier is a name used to identify a class, variable, function, or any other user-defined item. The basic rules for naming classes in VB.Net are as follows:
  • A name must begin with a letter that could be followed by a sequence of letters, digits (0 - 9) or underscore. The first character in an identifier cannot be a digit.
  • It must not contain any embedded space or symbol like ? - +! @ # % ^ & * ( ) [ ] { } . ; : " ' / and \. However an underscore ( _ ) can be used.
  • It should not be a reserved keyword.

VB.Net Keywords

The following table lists the VB.Net reserved keywords:
AddHandlerAddressOfAliasAndAndAlsoAsBoolean
ByRefByteByValCallCaseCatchCBool
CByteCCharCDateCDecCDblCharCInt
ClassCLngCObjConstContinueCSByteCShort
CSngCStrCTypeCUIntCULngCUShortDate
DecimalDeclareDefaultDelegateDimDirectCastDo
DoubleEachElseElseIfEndEnd IfEnum
EraseErrorEventExitFalseFinallyFor
FriendFunctionGetGetTypeGetXML
Namespace
GlobalGoTo
HandlesIfImplementsImportsInInheritsInteger
InterfaceIsIsNotLetLibLikeLong
LoopMeModModuleMustInheritMustOverrideMyBase
MyClassNamespaceNarrowingNewNextNotNothing
Not
Inheritable
Not
Overridable
ObjectOfOnOperatorOption
OptionalOrOrElseOverloadsOverridableOverridesParamArray
PartialPrivatePropertyProtectedPublicRaiseEventReadOnly
ReDimREMRemove
Handler
ResumeReturnSByteSelect
SetShadowsSharedShortSingleStaticStep
StopStringStructureSubSyncLockThenThrow
ToTrueTryTryCastTypeOfUIntegerWhile
WideningWithWithEventsWriteOnlyXor

VB.Net - Data Types

Data types refer to an extensive system used for declaring variables or functions of different types. The type of a variable determines how much space it occupies in storage and how the bit pattern stored is interpreted.

Data Types Available in VB.Net

VB.Net provides a wide range of data types. The following table shows all the data types available:
Data TypeStorage AllocationValue Range
BooleanDepends on implementing platformTrue or False
Byte1 byte0 through 255 (unsigned)
Char2 bytes0 through 65535 (unsigned)
Date8 bytes0:00:00 (midnight) on January 1, 0001 through 11:59:59 PM on December 31, 9999
Decimal16 bytes0 through +/-79,228,162,514,264,337,593,543,950,335 (+/-7.9...E+28)with no decimal point; 0 through +/-7.9228162514264337593543950335 with 28 places to the right of the decimal
Double8 bytes-1.79769313486231570E+308 through -4.94065645841246544E-324, for negative values
4.94065645841246544E-324 through 1.79769313486231570E+308, for positive values
Integer4 bytes-2,147,483,648 through 2,147,483,647 (signed)
Long8 bytes-9,223,372,036,854,775,808 through 9,223,372,036,854,775,807(signed)
Object4 bytes on 32-bit platform
8 bytes on 64-bit platform
Any type can be stored in a variable of type Object
SByte1 byte-128 through 127 (signed)
Short2 bytes-32,768 through 32,767 (signed)
Single4 bytes-3.4028235E+38 through -1.401298E-45 for negative values;
1.401298E-45 through 3.4028235E+38 for positive values
StringDepends on implementing platform0 to approximately 2 billion Unicode characters
UInteger4 bytes0 through 4,294,967,295 (unsigned)
ULong8 bytes0 through 18,446,744,073,709,551,615 (unsigned)
User-DefinedDepends on implementing platformEach member of the structure has a range determined by its data type and independent of the ranges of the other members
UShort2 bytes0 through 65,535 (unsigned)

Example

The following example demonstrates use of some of the types:
Module DataTypes
   Sub Main()
      Dim b As Byte
      Dim n As Integer
      Dim si As Single
      Dim d As Double
      Dim da As Date
      Dim c As Char
      Dim s As String
      Dim bl As Boolean
      b = 1
      n = 1234567
      si = 0.12345678901234566
      d = 0.12345678901234566
      da = Today
      c = "U"c
      s = "Me"
      If ScriptEngine = "VB" Then
         bl = True
      Else
         bl = False
      End If
      If bl Then
         'the oath taking
          Console.Write(c & " and," & s & vbCrLf)
          Console.WriteLine("declaring on the day of: {0}", da)
          Console.WriteLine("We will learn VB.Net seriously")
          Console.WriteLine("Lets see what happens to the floating point variables:")
          Console.WriteLine("The Single: {0}, The Double: {1}", si, d)
      End If
      Console.ReadKey()
   End Sub

End Module
When the above code is compiled and executed, it produces following result:
U and, Me
declaring on the day of: 12/4/2012 12:00:00 PM
We will learn VB.Net seriously
Lets see what happens to the floating point variables:
The Single:0.1234568, The Double: 0.123456789012346

The Type Conversion Functions in VB.Net

VB.Net provides the following inline type conversion functions:
S.NFunctionss & Description
1CBool(expression)
Converts the expression to Boolean data type.
2CByte(expression)
Converts the expression to Byte data type.
3CChar(expression)
Converts the expression to Char data type.
4CDate(expression)
Converts the expression to Date data type
5CDbl(expression)
Converts the expression to Double data type.
6CDec(expression)
Converts the expression to Decimal data type.
7CInt(expression)
Converts the expression to Integer data type.
8CLng(expression)
Converts the expression to Long data type.
9CObj(expression)
Converts the expression to Object type.
10CSByte(expression)
Converts the expression to SByte data type.
11CShort(expression)
Converts the expression to Short data type.
12CSng(expression)
Converts the expression to Single data type.
13CStr(expression)
Converts the expression to String data type.
14CUInt(expression)
Converts the expression to UInt data type.
15CULng(expression)
Converts the expression to ULng data type.
16CUShort(expression)
Converts the expression to UShort data type.

Example:

The following example demonstrates some of these functions:
Module DataTypes
   Sub Main()
      Dim n As Integer
      Dim da As Date
      Dim bl As Boolean = True
      n = 1234567
      da = Today
      Console.WriteLine(bl)
      Console.WriteLine(CSByte(bl))
      Console.WriteLine(CStr(bl))
      Console.WriteLine(CStr(da))
      Console.WriteLine(CChar(CChar(CStr(n))))
      Console.WriteLine(CChar(CStr(da)))
      Console.ReadKey()
   End Sub
End Module
When the above code is compiled and executed, it produces following result:
True
-1
True
12/4/2012
1
1

VB.Net - Variables

A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable in VB.Net has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.
We have already discussed various data types. The basic value types provided in VB.Net can be categorized as:
TypeExample
Integral typesSByte, Byte, Short, UShort, Integer, UInteger, Long, ULong and Char
Floating point typesSingle and Double
Decimal typesDecimal
Boolean typesTrue or False values, as assigned
Date typesDate
VB.Net also allows defining other value types of variable like Enum and reference types of variables likeClass. We will discuss date types and Classes, in subsequent chapters.

Variable Declaration in VB.Net

The Dim statement is used for variable declaration and storage allocation for one or more variables. The Dim statement is used at module, class, structure, procedure or block level.
Syntax for variable declaration in VB.Net is:
[ < attributelist> ] [ accessmodifier ] [[ Shared ] [ Shadows ] | [ Static ]]
[ ReadOnly ] Dim [ WithEvents ] variablelist
Where,
  • attributelist is a list of attributes that apply to the variable. Optional.
  • accessmodifier defines the access levels of the variables, it has values as - Public, Protected, Friend, Protected Friend and Private. Optional.
  • Shared declares a shared variable, which is not associated with any specific instance of a class or structure, rather available to all the instances of the class or structure. Optional.
  • Shadows indicate that the variable re-declares and hides an identically named element, or set of overloaded elements, in a base class. Optional.
  • Static indicates that the variable will retain its value, even when the after termination of the procedure in which it is declared. Optional.
  • ReadOnly means the variable can be read, but not written. Optional.
  • WithEvents specifies that the variable is used to respond to events raised by the instance assigned to the variable. Optional.
  • Variablelist provides the list of variables declared.
Each variable in the variable list has the following syntax and parts:
variablename[ ( [ boundslist ] ) ] [ As [ New ] datatype ] [ = initializer ]
Where,
  • variablename: is the name of the variable
  • boundslist: optional. It provides list of bounds of each dimension of an array variable.
  • New: optional. It creates a new instance of the class when the Dim statement runs.
  • datatype: Required if Option Strict is On. It specifies the data type of the variable.
  • initializer: Optional if New is not specified. Expression that is evaluated and assigned to the variable when it is created.
Some valid variable declarations along with their definition are shown here:
Dim StudentID As Integer
Dim StudentName As String
Dim Salary As Double
Dim count1, count2 As Integer
Dim status As Boolean
Dim exitButton As New System.Windows.Forms.Button
Dim lastTime, nextTime As Date

Variable Initialization in VB.Net

Variables are initialized (assigned a value) with an equal sign followed by a constant expression. The general form of initialization is:
variable_name = value;
for example,
Dim pi As Double
pi = 3.14159
You can initialize a variable at the time of declaration as follows:
Dim StudentID As Integer = 100
Dim StudentName As String = "Bill Smith"

Example

Try following example which makes use of various types of variables:
Module variablesNdataypes
   Sub Main()
      Dim a As Short
      Dim b As Integer
      Dim c As Double
      a = 10
      b = 20
      c = a + b
      Console.WriteLine("a = {0}, b = {1}, c = {2}", a, b, c)
      Console.ReadLine()
   End Sub
End Module
When the above code is compiled and executed, it produces following result:
a = 10, b = 20, c = 30

Accepting Values from User

The Console class in the System namespace provides a function ReadLine for accepting input from the user and store it into a variable. For example,
Dim message As String
message = Console.ReadLine
The following example demonstrates it:
Module variablesNdataypes
   Sub Main()
      Dim message As String
      Console.Write("Enter message: ")
      message = Console.ReadLine
      Console.WriteLine()
      Console.WriteLine("Your Message: {0}", message)
      Console.ReadLine()
   End Sub
End Module
When the above code is compiled and executed, it produces following result(Assume the user inputs Hello World):
Enter message: Hello World   
Your Message: Hello World

Lvalues and Rvalues

There are two kinds of expressions:
  1. lvalue : An expression that is an lvalue may appear as either the left-hand or right-hand side of an assignment.
  2. rvalue : An expression that is an rvalue may appear on the right- but not left-hand side of an assignment.
Variables are lvalues and so may appear on the left-hand side of an assignment. Numeric literals are rvalues and so may not be assigned and can not appear on the left-hand side. Following is a valid statement:
Dim g As Integer = 20
But following is not a valid statement and would generate compile-time error:
20 = g

VB.Net - Constants and Enumerations


The constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals.
Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are also enumeration constants as well.
The constants are treated just like regular variables except that their values cannot be modified after their definition.
An enumeration is a set of named integer constants.

Declaring Constants

In VB.Net, constants are declared using the Const statement. The Const statement is used at module, class, structure, procedure, or block level for use in place of literal values.
The syntax for the Const statement is:
[ < attributelist> ] [ accessmodifier ] [ Shadows ] 
Const constantlist
Where,
  • attributelist: specifies the list of attributes applied to the constants; you can provide multiple attributes, separated by commas. Optional.
  • accessmodifier: specifies which code can access these constants. Optional. Values can be either of the: Public, Protected, Friend, Protected Friend, or Private.
  • Shadows: this makes the constant hide a programming element of identical name, in a base class. Optional.
  • Constantlist: gives the list of names of constants declared. Required.
Where, each constant name has the following syntax and parts:
constantname [ As datatype ] = initializer
  • constantname: specifies the name of the constant
  • datatype: specifies the data type of the constant
  • initializer: specifies the value assigned to the constant
For example,
' The following statements declare constants.  
Const maxval As Long = 4999
Public Const message As String = "HELLO" 
Private Const piValue As Double = 3.1415

Example

The following example demonstrates declaration and use of a constant value:
Module constantsNenum
   Sub Main()
      Const PI = 3.14149
      Dim radius, area As Single
      radius = 7
      area = PI * radius * radius
      Console.WriteLine("Area = " & Str(area))
      Console.ReadKey()
   End Sub
End Module
When the above code is compiled and executed, it produces following result:
Area = 153.933

Print and Display Constants in VB.Net

VB.Net provides the following print and display constants:
ConstantDescription
vbCrLfCarriage return/linefeed character combination.
vbCrCarriage return character.
vbLfLinefeed character.
vbNewLineNewline character.
vbNullCharNull character.
vbNullStringNot the same as a zero-length string (""); used for calling external procedures.
vbObjectErrorError number. User-defined error numbers should be greater than this value. For example:
Err.Raise(Number) = vbObjectError + 1000
vbTabTab character.
vbBackBackspace character.

Declaring Enumerations

An enumerated type is declared using the Enum statement. The Enum statement declares an enumeration and defines the values of its members. The Enum statement can be used at the module, class, structure, procedure, or block level.
The syntax for the Enum statement is as follows:
[ < attributelist> ] [ accessmodifier ]  [ Shadows ] 
Enum enumerationname [ As datatype ] 
   memberlist
End Enum
Where,
  • attributelist: refers to the list of attributes applied to the variable. Optional.
  • asscessmodifier: specifies which code can access these enumerations. Optional. Values can be either of the: Public, Protected, Friend or Private.
  • Shadows: this makes the enumeration hide a programming element of identical name, in a base class. Optional.
  • enumerationname: name of the enumeration. Required
  • datatype: specifies the data type of the enumeration and all its members.
  • memberlist: specifies the list of member constants being declared in this statement. Required.
Each member in the memberlist has the following syntax and parts:
[< attribute list>] member name [ = initializer ]
Where,
  • name: specifies the name of the member. Required.
  • initializer: value assigned to the enumeration member. Optional.
For example,
Enum Colors
   red = 1
   orange = 2
   yellow = 3
   green = 4
   azure = 5
   blue = 6
   violet = 7
End Enum

Example

The following example demonstrates declaration and use of the Enum variable Colors:
Module constantsNenum
   Enum Colors
      red = 1
      orange = 2
      yellow = 3
      green = 4
      azure = 5
      blue = 6
      violet = 7
   End Enum
   Sub Main()
      Console.WriteLine("The Color Red is : " & Colors.red)
      Console.WriteLine("The Color Yellow is : " & Colors.yellow)
      Console.WriteLine("The Color Blue is : " & Colors.blue)
      Console.WriteLine("The Color Green is : " & Colors.green)
      Console.ReadKey()
   End Sub
End Module
When the above code is compiled and executed, it produces following result:
The Color Red is: 1
The Color Yellow is: 3
The Color Blue is: 6
The Color Green is: 4

VB.Net - Modifiers

The modifiers are keywords added with any programming element, to give some especial emphasis on how the programming element will behave, or will be accessed in the program
For example, the access modifiers: Public, Private, Protected, Friend, Protected Friend etc., indicates the access level of a programming element like a variable, constant, enumeration or a class.

List of Available Modifiers in VB.Net

The following table provides the complete list of VB.Net modifiers:
S.NModifierDescription
1AnsiSpecifies that Visual Basic should marshal all strings to American National Standards Institute (ANSI) values regardless of the name of the external procedure being declared.
2AssemblySpecifies that an attribute at the beginning of a source file applies to the entire assembly.
3AsyncIndicates that the method or lambda expression that it modifies is asynchronous. Such methods are referred to as async methods. The caller of an async method can resume its work without waiting for the async method to finish..
4AutoThe charsetmodifier part in the Declare statement supplies the character set information for marshaling strings during a call to the external procedure. It also affects how Visual Basic searches the external file for the external procedure name. The Auto modifier specifies that Visual Basic should marshal strings according to .NET Framework rules.
5ByRefSpecifies that an argument is passed by reference, i.e., the called procedure can change the value of a variable underlying the argument in the calling code. It is used under the contexts of:
  • Declare Statement
  • Function Statement
  • Sub Statement
6ByValSpecifies that an argument is passed in such a way that the called procedure or property cannot change the value of a variable underlying the argument in the calling code. It is used under the contexts of:
  • Declare Statement
  • unction Statement
  • Operator Statement
  • Property Statement
  • Sub Statement
7DefaultIdentifies a property as the default property of its class, structure, or interface.
8FriendSpecifies that one or more declared programming elements are accessible from within the assembly that contains their declaration, not only by the component that declares them.
Friend access is often the preferred level for an application's programming elements, and Friend is the default access level of an interface, a module, a class, or a structure.
9InIt is used in generic interfaces and delegates.
10IteratorSpecifies that a function or Get accessor is an iterator. An iteratorperforms a custom iteration over a collection.
11KeyThe Key keyword enables you to specify behavior for properties of anonymous types.
12ModuleSpecifies that an attribute at the beginning of a source file applies to the current assembly module. It is not same as the Module statement.
13MustInheritSpecifies that a class can be used only as a base class and that you cannot create an object directly from it.
14MustOverrideSpecifies that a property or procedure is not implemented in this class and must be overridden in a derived class before it can be used.
15NarrowingIndicates that a conversion operator (CType) converts a class or structure to a type that might not be able to hold some of the possible values of the original class or structure.
16NotInheritableSpecifies that a class cannot be used as a base class.
17NotOverridableSpecifies that a property or procedure cannot be overridden in a derived class.
18OptionalSpecifies that a procedure argument can be omitted when the procedure is called.
19OutFor generic type parameters, the Out keyword specifies that the type is covariant.
20OverloadsSpecifies that a property or procedure redeclares one or more existing properties or procedures with the same name.
21OverridableSpecifies that a property or procedure can be overridden by an identically named property or procedure in a derived class.
22OverridesSpecifies that a property or procedure overrides an identically named property or procedure inherited from a base class.
23ParamArrayParamArray allows you to pass an arbitrary number of arguments to the procedure. A ParamArray parameter is always declared using ByVal.
24PartialIndicates that a class or structure declaration is a partial definition of the class or structure.
25PrivateSpecifies that one or more declared programming elements are accessible only from within their declaration context, including from within any contained types.
26ProtectedSpecifies that one or more declared programming elements are accessible only from within their own class or from a derived class.
27PublicSpecifies that one or more declared programming elements have no access restrictions.
28ReadOnlySpecifies that a variable or property can be read but not written.
29ShadowsSpecifies that a declared programming element redeclares and hides an identically named element, or set of overloaded elements, in a base class.
30SharedSpecifies that one or more declared programming elements are associated with a class or structure at large, and not with a specific instance of the class or structure.
31StaticSpecifies that one or more declared local variables are to continue to exist and retain their latest values after termination of the procedure in which they are declared.
32UnicodeSpecifies that Visual Basic should marshal all strings to Unicode values regardless of the name of the external procedure being declared.
33WideningIndicates that a conversion operator (CType) converts a class or structure to a type that can hold all possible values of the original class or structure.
34WithEventsSpecifies that one or more declared member variables refer to an instance of a class that can raise events.
35WriteOnlySpecifies that a property can be written but not read.


VB.Net - Statements

statement is a complete instruction in Visual Basic programs. It may contain keywords, operators, variables, literal values, constants and expressions.
Statements could be categorized as:
  • Declaration statements - these are the statements where you name a variable, constant, or procedure, and can also specify a data type.
  • Executable statements - these are the statements, which initiate actions. These statements can call a method or function, loop or branch through blocks of code or assign values or expression to a variable or constant. In the last case, it is called an Assignment statement.

Declaration Statements

The declaration statements are used to name and define procedures, variables, properties, arrays, and constants. When you declare a programming element, you can also define its data type, access level, and scope.
The programming elements you may declare include variables, constants, enumerations, classes, structures, modules, interfaces, procedures, procedure parameters, function returns, external procedure references, operators, properties, events, and delegates.
Following are the declaration statements in VB.Net:
S.NStatements and DescriptionExample
1Dim Statement
Declares and allocates storage space for one or more variables.
Dim number As Integer
Dim quantity As Integer = 100
Dim message As String = "Hello!"
2Const Statement
Declares and defines one or more constants.
Const maximum As Long = 1000
Const naturalLogBase As Object 
= CDec(2.7182818284)
3Enum Statement
Declares an enumeration and defines the values of its members.
Enum CoffeeMugSize
    Jumbo
    ExtraLarge
    Large
    Medium
    Small
End Enum 
4Class Statement
Declares the name of a class and introduces the definition of the variables, properties, events, and procedures that the class comprises.
Class Box
Public length As Double
Public breadth As Double   
Public height As Double
End Class
5Structure Statement
Declares the name of a structure and introduces the definition of the variables, properties, events, and procedures that the structure comprises.
Structure Box
Public length As Double           
Public breadth As Double   
Public height As Double
End Structure
6Module Statement
Declares the name of a module and introduces the definition of the variables, properties, events, and procedures that the module comprises.
Public Module myModule
Sub Main()
Dim user As String = 
InputBox("What is your name?") 
MsgBox("User name is" & user)
End Sub 
End Module
7Interface Statement 
Declares the name of an interface and introduces the definitions of the members that the interface comprises.
Public Interface MyInterface
    Sub doSomething()
End Interface 
8Function Statement
Declares the name, parameters, and code that define a Function procedure.
Function myFunction
(ByVal n As Integer) As Double 
    Return 5.87 * n
End Function
9Sub Statement
Declares the name, parameters, and code that define a Sub procedure.
Sub mySub(ByVal s As String)
    Return
End Sub 
10Declare Statement
Declares a reference to a procedure implemented in an external file.
Declare Function getUserName
Lib "advapi32.dll" 
Alias "GetUserNameA" 
(
  ByVal lpBuffer As String, 
  ByRef nSize As Integer) As Integer 
11Operator Statement
Declares the operator symbol, operands, and code that define an operator procedure on a class or structure.
Public Shared Operator +
(ByVal x As obj, ByVal y As obj) As obj
        Dim r As New obj
' implemention code for r = x + y
        Return r
    End Operator 
12Property Statement
Declares the name of a property, and the property procedures used to store and retrieve the value of the property.
ReadOnly Property quote() As String 
    Get 
        Return quoteString
    End Get 
End Property
13Event Statement
Declares a user-defined event.
Public Event Finished()
14Delegate Statement
Used to declare a delegate.
Delegate Function MathOperator( 
    ByVal x As Double, 
    ByVal y As Double 
) As Double 

Executable Statements

An executable statement performs an action. Statements calling a procedure, branching to another place in the code, looping through several statements, or evaluating an expression are executable statements. An assignment statement is a special case of an executable statement.
Example
The following example demonstrates a decision making statement:
Module decisions
   Sub Main()
      'local variable definition '
      Dim a As Integer = 10

      ' check the boolean condition using if statement '
      If (a < 20) Then
         ' if condition is true then print the following '
         Console.WriteLine("a is less than 20")
      End If
      Console.WriteLine("value of a is : {0}", a)
      Console.ReadLine()
   End Sub
End Module
When the above code is compiled and executed, it produces following result:
a is less than 20;
value of a is : 10

VB.Net - Operators

An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. VB.Net is rich in built-in operators and provides following type of commonly used operators:
  • Arithmetic Operators
  • Comparison Operators
  • Logical/Bitwise Operators
  • Bit Shift Operators
  • Assignment Operators
  • Miscellaneous Operators
This tutorial will explain the most commonly used operators.

Arithmetic Operators

Following table shows all the arithmetic operators supported by VB.Net. Assume variable A holds 2 and variable B holds 7 then:
OperatorDescriptionExample
^Raises one operand to the power of anotherB^A will give 49
+Adds two operandsA + B will give 9
-Subtracts second operand from the firstA - B will give -5
*Multiply both operandsA * B will give 14
/Divide one operand by another and returns a floating point resultB / A will give 3.5
\Divide one operand by another and returns an integer resultB \ A will give 3
MODModulus Operator and remainder of after an integer divisionB MOD A will give 1

Comparison Operators

Following table shows all the comparison operators supported by VB.Net. Assume variable A holds 10 and variable B holds 20 then:
OperatorDescriptionExample
==Checks if the value of two operands is equal or not, if yes then condition becomes true.(A == B) is not true.
<>Checks if the value of two operands is equal or not, if values are not equal then condition becomes true.(A <> B) is true.
>Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.(A > B) is not true.
<Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.(A < B) is true.
>=Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.(A >= B) is not true.
<=Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.(A <= B) is true.
Apart from the above, VB.Net provides three more comparison operators, which we will be using in forthcoming chapters; however, we give a brief description here.
  • Is Operator - It compares two object reference variables and determines if two object references refer to the same object without performing value comparisons. If object1 and object2 both refer to the exact same object instance, result is True; otherwise, result is False.
  • IsNot Operator - It also compares two object reference variables and determines if two object references refer to different objects. If object1 and object2 both refer to the exact same object instance, result is False; otherwise, result is True.
  • Like Operator - It compares a string against a pattern.

Logical/Bitwise Operators

Following table shows all the logical operators supported by VB.Net. Assume variable A holds Boolean value True and variable B holds Boolean value False then:
Show Examples
OperatorDescriptionExample
AndIt is the logical as well as bitwise AND operator. If both the operands are true then condition becomes true. This operator does not perform short-circuiting, i.e., it evaluates both the expressions.(A And B) is False.
OrIt is the logical as well as bitwise OR operator. If any of the two operands is true then condition becomes true. This operator does not perform short-circuiting, i.e., it evaluates both the expressions.(A Or B) is True.
NotIt is the logical as well as bitwise NOT operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.Not(A And B) is True.
XorIt is the logical as well as bitwise Logical Exclusive OR operator. It returns True if both expressions are True or both expressions are False; otherwise it returns False. This operator does not perform short-circuiting, it always evaluates both expressions and there is no short-circuiting counterpart of this operatorA Xor B is True.
AndAlsoIt is the logical AND operator. It works only on Boolean data. It performs short-circuiting.(A AndAlso B) is False.
OrElseIt is the logical OR operator. It works only on Boolean data. It performs short-circuiting.(A OrElse B) is True.
IsFalseIt determines whether an expression is False.
IsTrueIt determines whether an expression is True.

Bit Shift Operators

We have already discussed the bitwise operators. The bit shift operators perform the shift operations on binary values. Before coming into the bit shift operators, let us understand the bit operations.
Bitwise operators work on bits and perform bit by bit operation. The truth tables for &, |, and ^ are as follows:
pqp & qp | qp ^ q
00000
01011
11110
10011
Assume if A = 60; and B = 13; Now in binary format they will be as follows:
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A  = 1100 0011
We have seen that the Bitwise operators supported by VB.Net are And, Or, Xor and Not. The Bit shift operators are >> and << for left shift and right shift respectively.
Assume that the variable A holds 60 and variable B holds 13 then:
Show Examples
OperatorDescriptionExample
AndBitwise AND Operator copies a bit to the result if it exists in both operands.(A AND B) will give 12 which is 0000 1100
OrBinary OR Operator copies a bit if it exists in either operand.(A Or B) will give 61 which is 0011 1101
XorBinary XOR Operator copies the bit if it is set in one operand but not both.(A Xor B) will give 49 which is 0011 0001
NotBinary Ones Complement Operator is unary and has the effect of 'flipping' bits.(Not A ) will give -60 which is 1100 0011
<<Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand.A << 2 will give 240 which is 1111 0000
>>Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand.A >> 2 will give 15 which is 0000 1111

Assignment Operators

There are following assignment operators supported by VB.Net:
Show Examples
OperatorDescriptionExample
=Simple assignment operator, Assigns values from right side operands to left side operandC = A + B will assign value of A + B into C
+=Add AND assignment operator, It adds right operand to the left operand and assign the result to left operandC += A is equivalent to C = C + A
-=Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operandC -= A is equivalent to C = C - A
*=Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operandC *= A is equivalent to C = C * A
/=Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand(floating point division)C /= A is equivalent to C = C / A
\=Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand (Integer division)C \= A is equivalent to C = C \A
^=Exponentiation and assignment operator. It raises the left operand to the power of the right operand and assigns the result to left operand.C^=A is equivalent to C = C ^ A
<<=Left shift AND assignment operatorC <<= 2 is same as C = C << 2
>>=Right shift AND assignment operatorC >>= 2 is same as C = C >> 2
&=Concatenates a String expression to a String variable or property and assigns the result to the variable or property.Str1 &= Str2 is same as
Str1 = Str1 & Str2

Miscellaneous Operators

There are few other important operators supported by VB.Net.
Show Examples
OperatorDescriptionExample
AddressOfReturns the address of a procedure.
AddHandler Button1.Click,
AddressOf Button1_Click
AwaitIt is applied to an operand in an asynchronous method or lambda expression to suspend execution of the method until the awaited task completes.
 Dim result As res
= Await AsyncMethodThatReturnsResult()
Await AsyncMethod()
GetTypeIt returns a Type object for the specified type. The Type object provides information about the type such as its properties, methods, and events.
MsgBox(GetType(Integer).ToString())
Function ExpressionIt declares the parameters and code that define a function lambda expression.
Dim add5 = Function(num As
 Integer) num + 5
'prints 10
Console.WriteLine(add5(5))
IfIt uses short-circuit evaluation to conditionally return one of two values. The If operator can be called with three arguments or with two arguments.
Dim num = 5
Console.WriteLine(If(num >= 0,
"Positive", "Negative"))

Operators Precedence in VB.Net

Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator:
For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher precedence than + so it first get multiplied with 3*2 and then adds into 7.
Here operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
Show Examples
OperatorPrecedence
AwaitHighest
Exponentiation (^)
Unary identity and negation (+, -)
Multiplication and floating-point division (*, /)
Integer division (\)
Modulus arithmetic (Mod)
Addition and subtraction (+, -)
Arithmetic bit shift (<<, >>)
All comparison operators (=, <>, <, <=, >, >=, Is, IsNot, Like, TypeOf...Is)
Negation (Not)
Conjunction (And, AndAlso)
Inclusive disjunction (Or, OrElse)
Exclusive disjunction (Xor)Lowest

VB.Net - Decision Making

Decision making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.
Following is the general from of a typical decision making structure found in most of the programming languages:
Decision making statements in VB.Net
VB.Net provides following types of decision making statements. Click the following links to check their detail.
StatementDescription
If ... Then statementAn If...Then statement consists of a boolean expression followed by one or more statements.
If...Then...Else statementAn If...Then statement can be followed by an optional Else statement, which executes when the boolean expression is false.
nested If statementsYou can use one If or Else if statement inside another If or Else if statement(s).
Select Case statementSelect Case statement allows a variable to be tested for equality against a list of values.
nested Select Case statementsYou can use one select case statement inside another select case statement(s).

VB.Net - Loops

There may be a situation when you need to execute a block of code several number of times. In general statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times and following is the general from of a loop statement in most of the programming languages:
Loop Architecture
VB.Net provides following types of loop to handle looping requirements. Click the following links to check their detail.
Loop TypeDescription
Do LoopIt repeats the enclosed block of statements while a Boolean condition is True or until the condition becomes True. It could be terminated at any time with the Exit Do statement.
For...NextIt repeats a group of statements a specified number of times and a loop index counts the number of loop iterations as the loop executes.
For Each...NextIt repeats a group of statements for each element in a collection. This loop is used for accessing and manipulating all elements in an array or a VB.Net collection.
While... End WhileIt executes a series of statements as long as a given condition is True.
With... End WithIt is not exactly a looping construct. It executes a series of statements that repeatedly refers to a single object or structure.
Nested loopsYou can use one or more loop inside any another While, For or Do loop.

Loop Control Statements:

Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.
VB.Net provides the following control statements. Click the following links to check their detail.
Control StatementDescription
Exit statementTerminates the loop or select case statement and transfers execution to the statement immediately following the loop or select case.
Continue statementCauses the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
GoTo statementTransfers control to the labeled statement. Though it is not advised to use GoTo statement in your program.

VB.Net - Strings

In VB.Net you can use strings as array of characters, however, more common practice is to use the String keyword to declare a string variable. The string keyword is an alias for the System.String class.

Creating a String Object

You can create string object using one of the following methods:
  • By assigning a string literal to a String variable
  • By using a String class constructor
  • By using the string concatenation operator (+)
  • By retrieving a property or calling a method that returns a string
  • By calling a formatting method to convert a value or object to its string representation
The following example demonstrates this:
Module strings
   Sub Main()
      Dim fname, lname, fullname, greetings As String
      fname = "Rowan"
      lname = "Atkinson"
      fullname = fname + " " + lname
      Console.WriteLine("Full Name: {0}", fullname)

     'by using string constructor
      Dim letters As Char() = {"H", "e", "l", "l", "o"}
      greetings = New String(letters)
      Console.WriteLine("Greetings: {0}", greetings)

      'methods returning String
      Dim sarray() As String = {"Hello", "From", "Tutorials", "Point"}
      Dim message As String = String.Join(" ", sarray)
      Console.WriteLine("Message: {0}", message)

      'formatting method to convert a value 
      Dim waiting As DateTime = New DateTime(2012, 12, 12, 17, 58, 1)
      Dim chat As String = String.Format("Message sent at {0:t} on {0:D}", waiting)
      Console.WriteLine("Message: {0}", chat)
      Console.ReadLine()
   End Sub
End Module
When the above code is compiled and executed, it produces following result:
Full Name: Rowan Atkinson
Greetings: Hello
Message: Hello From Tutorials Point
Message: Message sent at 5:58 PM on Wednesday, December 12, 2012

Properties of the String Class

The String class has the following two properties:
S.NProperty Name & Description
1Chars
Gets the Char object at a specified position in the current String object.
2Length
Gets the number of characters in the current String object.

Methods of the String Class

The String class has numerous methods that help you in working with the string objects. The following table provides some of the most commonly used methods:
S.NMethod Name & Description
1Public Shared Function Compare ( strA As String, strB As String ) As Integer 
Compares two specified string objects and returns an integer that indicates their relative position in the sort order.
2Public Shared Function Compare ( strA As String, strB As String, ignoreCase As Boolean ) As Integer 
Compares two specified string objects and returns an integer that indicates their relative position in the sort order. However, it ignores case if the Boolean parameter is true.
3Public Shared Function Concat ( str0 As String, str1 As String ) As String 
Concatenates two string objects.
4Public Shared Function Concat ( str0 As String, str1 As String, str2 As String ) As String 
Concatenates three string objects.
5Public Shared Function Concat ( str0 As String, str1 As String, str2 As String, str3 As String ) As String 
Concatenates four string objects.
6Public Function Contains ( value As String ) As Boolean 
Returns a value indicating whether the specified string object occurs within this string.
7Public Shared Function Copy ( str As String ) As String 
Creates a new String object with the same value as the specified string.
8pPublic Sub CopyTo ( sourceIndex As Integer, destination As Char(), destinationIndex As Integer, count As Integer ) 
Copies a specified number of characters from a specified position of the string object to a specified position in an array of Unicode characters.
9Public Function EndsWith ( value As String ) As Boolean 
Determines whether the end of the string object matches the specified string.
10Public Function Equals ( value As String ) As Boolean 
Determines whether the current string object and the specified string object have the same value.
11Public Shared Function Equals ( a As String, b As String ) As Boolean 
Determines whether two specified string objects have the same value.
12Public Shared Function Format ( format As String, arg0 As Object ) As String 
Replaces one or more format items in a specified string with the string representation of a specified object.
13Public Function IndexOf ( value As Char ) As Integer 
Returns the zero-based index of the first occurrence of the specified Unicode character in the current string.
14Public Function IndexOf ( value As String ) As Integer 
Returns the zero-based index of the first occurrence of the specified string in this instance.
15Public Function IndexOf ( value As Char, startIndex As Integer ) As Integer 
Returns the zero-based index of the first occurrence of the specified Unicode character in this string, starting search at the specified character position.
16Public Function IndexOf ( value As String, startIndex As Integer ) As Integer 
Returns the zero-based index of the first occurrence of the specified string in this instance, starting search at the specified character position.
17Public Function IndexOfAny ( anyOf As Char() ) As Integer 
Returns the zero-based index of the first occurrence in this instance of any character in a specified array of Unicode characters.
18Public Function IndexOfAny ( anyOf As Char(), startIndex As Integer ) As Integer 
Returns the zero-based index of the first occurrence in this instance of any character in a specified array of Unicode characters, starting search at the specified character position.
19Public Function Insert ( startIndex As Integer, value As String ) As String 
Returns a new string in which a specified string is inserted at a specified index position in the current string object.
20Public Shared Function IsNullOrEmpty ( value As String ) As Boolean 
Indicates whether the specified string is null or an Empty string.
21Public Shared Function Join ( separator As String, ParamArray value As String() ) As String 
Concatenates all the elements of a string array, using the specified separator between each element.
22Public Shared Function Join ( separator As String, value As String(), startIndex As Integer, count As Integer ) As String 
Concatenates the specified elements of a string array, using the specified separator between each element.
23Public Function LastIndexOf ( value As Char ) As Integer 
Returns the zero-based index position of the last occurrence of the specified Unicode character within the current string object.
24Public Function LastIndexOf ( value As String ) As Integer 
Returns the zero-based index position of the last occurrence of a specified string within the current string object.
25Public Function Remove ( startIndex As Integer ) As String 
Removes all the characters in the current instance, beginning at a specified position and continuing through the last position, and returns the string.
26Public Function Remove ( startIndex As Integer, count As Integer ) As String 
Removes the specified number of characters in the current string beginning at a specified position and returns the string.
27Public Function Replace ( oldChar As Char, newChar As Char ) As String 
Replaces all occurrences of a specified Unicode character in the current string object with the specified Unicode character and returns the new string.
28Public Function Replace ( oldValue As String, newValue As String ) As String 
Replaces all occurrences of a specified string in the current string object with the specified string and returns the new string.
29Public Function Split ( ParamArray separator As Char() ) As String() 
Returns a string array that contains the substrings in the current string object, delimited by elements of a specified Unicode character array.
30Public Function Split ( separator As Char(), count As Integer ) As String() 
Returns a string array that contains the substrings in the current string object, delimited by elements of a specified Unicode character array. The int parameter specifies the maximum number of substrings to return.
31Public Function StartsWith ( value As String ) As Boolean 
Determines whether the beginning of this string instance matches the specified string.
32Public Function ToCharArray As Char()
Returns a Unicode character array with all the characters in the current string object.
33Public Function ToCharArray ( startIndex As Integer, length As Integer ) As Char() 
Returns a Unicode character array with all the characters in the current string object, starting from the specified index and up to the specified length.
34Public Function ToLower As String
Returns a copy of this string converted to lowercase.
35Public Function ToUpper As String
Returns a copy of this string converted to uppercase.
36Public Function Trim As String
Removes all leading and trailing white-space characters from the current String object.
The above list of methods is not exhaustive, please visit MSDN library for the complete list of methods and String class constructors.

Examples:

The following example demonstrates some of the methods mentioned above:
Comparing Strings:
#include <include.h>
Module strings
   Sub Main()
      Dim str1, str2 As String
      str1 = "This is test"
      str2 = "This is text"
      If (String.Compare(str1, str2) = 0) Then
          Console.WriteLine(str1 + " and " + str2 +
                            " are equal.")
      Else
          Console.WriteLine(str1 + " and " + str2 +
                            " are not equal.")
      End If
      Console.ReadLine()
   End Sub
End Module
When the above code is compiled and executed, it produces following result:
This is test and This is text are not equal.
String Contains String:
Module strings
   Sub Main()
      Dim str1 As String
      str1 = "This is test"
      If (str1.Contains("test")) Then
          Console.WriteLine("The sequence 'test' was found.")
      End If
      Console.ReadLine()
   End Sub
End Module
When the above code is compiled and executed, it produces following result:
The sequence 'test' was found.
Getting a Substring:
Module strings
   Sub Main()
      Dim str As String
      str = "Last night I dreamt of San Pedro"
      Console.WriteLine(str)
      Dim substr As String = str.Substring(23)
      Console.WriteLine(substr)
      Console.ReadLine()
   End Sub
End Module
When the above code is compiled and executed, it produces following result:
Last night I dreamt of San Pedro
San Pedro.
Joining Strings:
Module strings
   Sub Main()
      Dim strarray As String() = {"Down the way where the nights are gay",
                          "And the sun shines daily on the mountain top",
                           "I took a trip on a sailing ship",
                          "And when I reached Jamaica",
                          "I made a stop"}
      Dim str As String = String.Join(vbCrLf, strarray)
      Console.WriteLine(str)
      Console.ReadLine()
   End Sub
End Module
When the above code is compiled and executed, it produces following result:
Down the way where the nights are gay
And the sun shines daily on the mountain top
I took a trip on a sailing ship
And when I reached Jamaica
I made a stop

VB.Net - Arrays

An array stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.
Arrays in VB.Net

Creating Arrays in VB.Net

To declare an array in VB.Net, you use the Dim statement. For example,
Dim intData(30)	  ' an array of 31 elements
Dim strData(20) As String	' an array of 21 strings
Dim twoDarray(10, 20) As Integer	'a two dimensional array of integers
Dim ranges(10, 100)	 'a two dimensional array
You can also initialize the array elements while declaring the array. For example,
Dim intData() As Integer = {12, 16, 20, 24, 28, 32}
Dim names() As String = {"Karthik", "Sandhya", _
"Shivangi", "Ashwitha", "Somnath"}
Dim miscData() As Object = {"Hello World", 12d, 16ui, "A"c}
The elements in an array can be stored and accessed by using the index of the array. The following program demonstrates this:
Module arrayApl
   Sub Main()
      Dim n(10) As Integer  ' n is an array of 11 integers '
      Dim i, j As Integer
      ' initialize elements of array n '         
      For i = 0 To 10
          n(i) = i + 100 ' set element at location i to i + 100 
      Next i
      ' output each array element's value '
      For j = 0 To 10
          Console.WriteLine("Element({0}) = {1}", j, n(j))
      Next j
      Console.ReadKey()
   End Sub
End Module
When the above code is compiled and executed, it produces following result:
Element(0) = 100
Element(1) = 101
Element(2) = 102
Element(3) = 103
Element(4) = 104
Element(5) = 105
Element(6) = 106
Element(7) = 107
Element(8) = 108
Element(9) = 109
Element(10) = 110

Dynamic Arrays

Dynamic arrays are arrays that can be dimensioned and re-dimensioned as par the need of the program. You can declare a dynamic array using the ReDim statement.
Syntax for ReDim statement:
ReDim [Preserve] arrayname(subscripts)
Where,
  • The Preserve keyword helps to preserve the data in an existing array, when you resize it.
  • arrayname is the name of the array to re-dimension
  • subscripts specifies the new dimension.
Module arrayApl
   Sub Main()
      Dim marks() As Integer
      ReDim marks(2)
      marks(0) = 85
      marks(1) = 75
      marks(2) = 90
      ReDim Preserve marks(10)
      marks(3) = 80
      marks(4) = 76
      marks(5) = 92
      marks(6) = 99
      marks(7) = 79
      marks(8) = 75
      For i = 0 To 10
          Console.WriteLine(i & vbTab & marks(i))
      Next i
      Console.ReadKey()
   End Sub
End Module
When the above code is compiled and executed, it produces following result:
0	85
1	75
2	90
3	80
4	76
5	92
6	99
7	79
8	75
9	0
10	0

Multi-Dimensional Arrays

VB.Net allows multidimensional arrays. Multi-dimensional arrays are also called rectangular array.
You can declare a 2 dimensional array of strings as:
Dim twoDStringArray(10, 20) As String
or, a three dimensional array of Integer variables:
Dim threeDIntArray(10, 10, 10) As Integer
The following program demonstrates creating and using a two dimensional array:
Module arrayApl
   Sub Main()
      ' an array with 5 rows and 2 columns
      Dim a(,) As Integer = {{0, 0}, {1, 2}, {2, 4}, {3, 6}, {4, 8}}
      Dim i, j As Integer
      ' output each array element's value '
      For i = 0 To 4
          For j = 0 To 1
              Console.WriteLine("a[{0},{1}] = {2}", i, j, a(i, j))
          Next j
      Next i
      Console.ReadKey()
   End Sub
End Module
When the above code is compiled and executed, it produces following result:
a[0,0]: 0
a[0,1]: 0
a[1,0]: 1
a[1,1]: 2
a[2,0]: 2
a[2,1]: 4
a[3,0]: 3
a[3,1]: 6
a[4,0]: 4
a[4,1]: 8

Jagged Array

A Jagged array is an array of arrays. The follwoing code shows declaring a jagged array named scoresof Integers:
Dim scores As Integer()() = New Integer(5)(){}
The following example illustrates using a jagged array:
Module arrayApl
   Sub Main()
      'a jagged array of 5 array of integers
      Dim a As Integer()() = New Integer(4)() {}
      a(0) = New Integer() {0, 0}
      a(1) = New Integer() {1, 2}
      a(2) = New Integer() {2, 4}
      a(3) = New Integer() {3, 6}
      a(4) = New Integer() {4, 8}
      Dim i, j As Integer
      ' output each array element's value 
      For i = 0 To 4
          For j = 0 To 1
              Console.WriteLine("a[{0},{1}] = {2}", i, j, a(i)(j))
          Next j
      Next i
      Console.ReadKey()
   End Sub
End Module
When the above code is compiled and executed, it produces following result:
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8

The Array Class

The Array class is the base class for all the arrays in VB.Net. It is defined in the System namespace. The Array class provides various properties and methods to work with arrays.

Properties of the Array Class

The following table provides some of the most commonly used properties of the Array class:
S.NProperty Name & Description
1IsFixedSize
Gets a value indicating whether the Array has a fixed size.
2IsReadOnly
Gets a value indicating whether the Array is read-only.
3Length
Gets a 32-bit integer that represents the total number of elements in all the dimensions of the Array.
4LongLength
Gets a 64-bit integer that represents the total number of elements in all the dimensions of the Array.
5Rank
Gets the rank (number of dimensions) of the Array.

Methods of the Array Class

The following table provides some of the most commonly used methods of the Array class:
S.NMethod Name & Description
1Public Shared Sub Clear ( array As Array, index As Integer, length As Integer ) 
Sets a range of elements in the Array to zero, to false, or to null, depending on the element type.
2Public Shared Sub Copy ( sourceArray As Array, destinationArray As Array, length As Integer ) 
Copies a range of elements from an Array starting at the first element and pastes them into another Array starting at the first element. The length is specified as a 32-bit integer.
3Public Sub CopyTo ( array As Array, index As Integer ) 
Copies all the elements of the current one-dimensional Array to the specified one-dimensional Array starting at the specified destination Array index. The index is specified as a 32-bit integer.
4Public Function GetLength ( dimension As Integer ) As Integer 
Gets a 32-bit integer that represents the number of elements in the specified dimension of the Array.
5Public Function GetLongLength ( dimension As Integer ) As Long 
Gets a 64-bit integer that represents the number of elements in the specified dimension of the Array.
6Public Function GetLowerBound ( dimension As Integer ) As Integer 
Gets the lower bound of the specified dimension in the Array.
7Public Function GetType As Type
Gets the Type of the current instance. (Inherited from Object.)
8Public Function GetUpperBound ( dimension As Integer ) As Integer 
Gets the upper bound of the specified dimension in the Array.
9Public Function GetValue ( index As Integer ) As Object 
Gets the value at the specified position in the one-dimensional Array. The index is specified as a 32-bit integer.
10Public Shared Function IndexOf ( array As Array, value As Object ) As Integer 
Searches for the specified object and returns the index of the first occurrence within the entire one-dimensional Array.
11Public Shared Sub Reverse ( array As Array ) 
Reverses the sequence of the elements in the entire one-dimensional Array.
12Public Sub SetValue ( value As Object, index As Integer ) 
Sets a value to the element at the specified position in the one-dimensional Array. The index is specified as a 32-bit integer.
13Public Shared Sub Sort ( array As Array ) 
Sorts the elements in an entire one-dimensional Array using the IComparable implementation of each element of the Array.
14Public Overridable Function ToString As String
eturns a string that represents the current object. (Inherited from Object.)
For complete list of Array class properties and methods, please consult Microsoft documentation.

Example

The following program demonstrates use of some of the methods of the Array class:
Module arrayApl
   Sub Main()
      Dim list As Integer() = {34, 72, 13, 44, 25, 30, 10}
      Dim temp As Integer() = list
      Dim i As Integer
      Console.Write("Original Array: ")
      For Each i In list
          Console.Write("{0} ", i)
      Next i
      Console.WriteLine()
      ' reverse the array
      Array.Reverse(temp)
      Console.Write("Reversed Array: ")
      For Each i In temp
          Console.Write("{0} ", i)
      Next i
      Console.WriteLine()
      'sort the array
      Array.Sort(list)
      Console.Write("Sorted Array: ")
      For Each i In list
          Console.Write("{0} ", i)
      Next i
      Console.WriteLine()
      Console.ReadKey()
   End Sub
End Module
When the above code is compiled and executed, it produces following result:
Original Array: 34 72 13 44 25 30 10
Reversed Array: 10 30 25 44 13 72 34
Sorted Array: 10 13 25 30 34 44 72

VB.Net - Functions

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 procedure. VB.Net has two types of procedures:
  • Functions
  • Sub procedures or Subs
Functions return a value, where Subs do not return a value.

Defining a Function

The Function statement is used to declare the name, parameter and the body of a function. The syntax for the Function statement is:
[Modifiers] Function FunctionName [(ParameterList)] As ReturnType
    [Statements]
End Function
Where,
Tutorial content goes here.....
  • Modifiers: specifiy 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

Following code snippet shows a function FindMax that takes two integer values and returns the larger of the two.
Function FindMax(ByVal num1 As Integer, ByVal num2 As Integer) As Integer
   ' local variable declaration */
   Dim result As Integer
   If (num1 > num2) Then
       result = num1
   Else
       result = num2
   End If
   FindMax = result
End Function

Function Returning a Value

In VB.Net a function can return a value to the calling code in two ways:
  • By using the return statement
  • By assigning the value to the function name
The following example demonstrates using the FindMax function:
Module myfunctions
   Function FindMax(ByVal num1 As Integer, ByVal num2 As Integer) As Integer
      ' local variable declaration */
      Dim result As Integer
      If (num1 > num2) Then
          result = num1
      Else
          result = num2
      End If
      FindMax = result
   End Function
   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
When the above code is compiled and executed, it produces following result:
Max value is : 200

Recursive Function

A function can call itself. This is known as recursion. Following is an example that calculates factorial for a given number using a recursive function:
Module myfunctions
   Function factorial(ByVal num 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()
      'calling the factorial method
      Console.WriteLine("Factorial of 6 is : {0}", factorial(6))
      Console.WriteLine("Factorial of 7 is : {0}", factorial(7))
      Console.WriteLine("Factorial of 8 is : {0}", factorial(8))
      Console.ReadLine()
   End Sub
End Module
When the above code is compiled and executed, it produces following result:
Factorial of 6 is: 720
Factorial of 7 is: 5040
Factorial of 8 is: 40320

Param Arrays

At times, while declaring a function or sub procedure you are not sure of the number of arguments passed as a parameter. VB.Net param arrays (or parameter arrays) come into help at these times.
The following example demonstrates this:
Module myparamfunc
   Function AddElements(ParamArray arr As Integer()) As Integer
      Dim sum As Integer = 0
      Dim i As Integer = 0
      For Each i In arr
          sum += i
      Next i
      Return sum
   End Function
   Sub Main()
      Dim sum As Integer
      sum = AddElements(512, 720, 250, 567, 889)
      Console.WriteLine("The sum is: {0}", sum)
      Console.ReadLine()
   End Sub
End Module
When the above code is compiled and executed, it produces following result:
The sum is: 2938

Passing Arrays as Function Arguments

You can pass an array as a function argument in VB.Net. The following example demonstrates this:
Module arrayParameter
   Function getAverage(ByVal arr As Integer(), ByVal size As Integer) As Double
      'local variables
       Dim i As Integer
       Dim avg As Double
       Dim sum As Integer = 0
       For i = 0 To size - 1
           sum += arr(i)
       Next i
       avg = sum / size
       Return avg
    End Function
    Sub Main()
        ' an int array with 5 elements '
        Dim balance As Integer() = {1000, 2, 3, 17, 50}
        Dim avg As Double
        'pass pointer to the array as an argument 
        avg = getAverage(balance, 5)
        ' output the returned value '
        Console.WriteLine("Average value is: {0} ", avg)
        Console.ReadLine()
    End Sub
End Module
When the above code is compiled and executed, it produces following result:
Average value is: 214.4

VB.Net - Classes & Objects

When you define a class, you define a blueprint for a data type. This doesn't actually define any data, but it does define what the class name means, that is, what an object of the class will consist of and what operations can be performed on such an object.
Objects are instances of a class. The methods and variables that constitute a class are called members of the class.

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 following example demonstrates a Box class, with three data members, length, breadth and height:
Module mybox
   Class Box
      Public length As Double   ' Length of a box
      Public breadth As Double   ' Breadth of a box
      Public height As Double    ' Height of a box
   End Class
   Sub Main()
      Dim Box1 As Box = New Box()        ' Declare Box1 of type Box
      Dim Box2 As Box = New Box()        ' Declare Box2 of type Box
      Dim volume As Double = 0.0     ' Store the volume of a box here
      ' box 1 specification
      Box1.height = 5.0
      Box1.length = 6.0
      Box1.breadth = 7.0
       ' box 2 specification
      Box2.height = 10.0
      Box2.length = 12.0	
      Box2.breadth = 13.0
      'volume of box 1
      volume = Box1.height * Box1.length * Box1.breadth
      Console.WriteLine("Volume of Box1 : {0}", volume)
      'volume of box 2
      volume = Box2.height * Box2.length * Box2.breadth
      Console.WriteLine("Volume of Box2 : {0}", volume)
      Console.ReadKey()
   End Sub
End Module
When the above code is compiled and executed, it produces following result:
Volume of Box1 : 210
Volume of Box2 : 1560

Member Functions and Encapsulation

A member function of a class is a function that has its definition or its prototype within the class definition like any other variable. It operates on any object of the class of which it is a member, and has access to all the members of a class for that object.
Member variables are attributes of an object (from design perspective) and they are kept private to implement encapsulation. These variables can only be accessed using the public member functions.
Let us put above concepts to set and get the value of different class members in a class:
Module mybox
   Class Box
      Public length As Double   ' Length of a box
      Public breadth As Double   ' Breadth of a box
      Public height As Double    ' Height of a box
      Public Sub setLength(ByVal len As Double)
          length = len
      End Sub
      Public Sub setBreadth(ByVal bre As Double)
          breadth = bre
      End Sub
      Public Sub setHeight(ByVal hei As Double)
          height = hei
      End Sub
      Public Function getVolume() As Double
          Return length * breadth * height
      End Function
   End Class
   Sub Main()
      Dim Box1 As Box = New Box()        ' Declare Box1 of type Box
      Dim Box2 As Box = New Box()        ' Declare Box2 of type Box
      Dim volume As Double = 0.0     ' Store the volume of a box here

     ' box 1 specification
      Box1.setLength(6.0)
      Box1.setBreadth(7.0)
      Box1.setHeight(5.0)
      
      'box 2 specification
      Box2.setLength(12.0)
      Box2.setBreadth(13.0)
      Box2.setHeight(10.0)
      
      ' volume of box 1
      volume = Box1.getVolume()
      Console.WriteLine("Volume of Box1 : {0}", volume)

      'volume of box 2
      volume = Box2.getVolume()
      Console.WriteLine("Volume of Box2 : {0}", volume)
      Console.ReadKey()
   End Sub
End Module
When the above code is compiled and executed, it produces following result:
Volume of Box1 : 210
Volume of Box2 : 1560

Constructors and Destructors

A class constructor is a special member Sub of a class that is executed whenever we create new objects of that class. A constructor has the name New and it does not have any return type.
Following program explain the concept of constructor:
Class Line
   Private length As Double    ' Length of a line
   Public Sub New()   'constructor
      Console.WriteLine("Object is being created")
   End Sub
   Public Sub setLength(ByVal len As Double)
      length = len
   End Sub
     
   Public Function getLength() As Double
      Return length
   End Function
   Shared Sub Main()
      Dim line As Line = New Line()
      'set line length
      line.setLength(6.0)
      Console.WriteLine("Length of line : {0}", line.getLength())
      Console.ReadKey()
   End Sub
End Class
When the above code is compiled and executed, it produces following result:
Object is being created
Length of line : 6
A default constructor does not have any parameter but if you need a constructor can have parameters. Such constructors are called parameterized constructors. This technique helps you to assign initial value to an object at the time of its creation as shown in the following example:
Class Line
   Private length As Double    ' Length of a line
   Public Sub New(ByVal len As Double)   'parameterised constructor
      Console.WriteLine("Object is being created, length = {0}", len)
      length = len
   End Sub
   Public Sub setLength(ByVal len As Double)
      length = len
   End Sub
       
   Public Function getLength() As Double
      Return length
   End Function
   Shared Sub Main()
      Dim line As Line = New Line(10.0)
      Console.WriteLine("Length of line set by constructor : {0}", line.getLength())
      'set line length
      line.setLength(6.0)
      Console.WriteLine("Length of line set by setLength : {0}", line.getLength())
      Console.ReadKey()
   End Sub
End Class
When the above code is compiled and executed, it produces following result:
Object is being created, length = 10
Length of line set by constructor : 10
Length of line set by setLength : 6
destructor is a special member Sub of a class that is executed whenever an object of its class goes out of scope.
destructor has the name Finalize and it can neither return a value nor can it take any parameters. Destructor can be very useful for releasing resources before coming out of the program like closing files, releasing memories etc.
Destructors cannot be inherited or overloaded.
Following example explain the concept of destructor:
Class Line
   Private length As Double    ' Length of a line
   Public Sub New()   'parameterised constructor
      Console.WriteLine("Object is being created")
   End Sub
   Protected Overrides Sub Finalize()  ' destructor
      Console.WriteLine("Object is being deleted")
   End Sub
   Public Sub setLength(ByVal len As Double)
      length = len
   End Sub
   Public Function getLength() As Double
      Return length
   End Function
   Shared Sub Main()
      Dim line As Line = New Line()
      'set line length
      line.setLength(6.0)
      Console.WriteLine("Length of line : {0}", line.getLength())
      Console.ReadKey()
   End Sub
End Class
When the above code is compiled and executed, it produces following result:
Object is being created
Length of line : 6
Object is being deleted

Shared Members of a VB.Net Class

We can define class members as static using the Shared keyword. When we declare a member of a class as Shared it means no matter how many objects of the class are created, there is only one copy of the member.
The keyword Shared implies that only one instance of the member exists for a class. Shared variables are used for defining constants because their values can be retrieved by invoking the class without creating an instance of it.
Shared variables can be initialized outside the member function or class definition. You can also initialize Shared variables inside the class definition.
You can also declare a member function as Shared. Such functions can access only Shared variables. The Shared functions exist even before the object is created.
The following example demonstrates the use of shared members:
Class StaticVar
   Public Shared num As Integer
   Public Sub count()
      num = num + 1
   End Sub
   Public Shared Function getNum() As Integer
      Return num
   End Function
   Shared Sub Main()
      Dim s As StaticVar = New StaticVar()
      s.count()
      s.count()
      s.count()
      Console.WriteLine("Value of variable num: {0}", StaticVar.getNum())
      Console.ReadKey()
   End Sub
End Class
When the above code is compiled and executed, it produces following result:
Value of variable num: 3

Inheritance

One of the most important concepts in object-oriented programming is that of inheritance. Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and fast implementation time.
When creating a class, instead of writing completely new data members and member functions, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the base class, and the new class is referred to as the derived class.

Base & Derived Classes:

A class can be derived from more than one class or interface, which means that it can inherit data and functions from multiple base class or interface.
The syntax used in VB.Net for creating derived classes is as follows:
<access-specifier> Class <base_class>
...
End Class
Class <derived_class>: Inherits <base_class>
...
End Class
Consider a base class Shape and its derived class Rectangle:
' Base class
Class Shape
   Protected width As Integer
   Protected height As Integer
   Public Sub setWidth(ByVal w As Integer)
      width = w
   End Sub
   Public Sub setHeight(ByVal h As Integer)
      height = h
   End Sub
End Class
' Derived class
Class Rectangle : Inherits Shape
   Public Function getArea() As Integer
      Return (width * height)
   End Function
End Class
Class RectangleTester
   Shared Sub Main()
      Dim rect As Rectangle = New Rectangle()
      rect.setWidth(5)
      rect.setHeight(7)
      ' Print the area of the object.
      Console.WriteLine("Total area: {0}", rect.getArea())
      Console.ReadKey()
   End Sub	
End Class
When the above code is compiled and executed, it produces following result:
Total area: 35

Base Class Initialization

The derived class inherits the base class member variables and member methods. Therefore the super class object should be created before the subclass is created. The super class or the base class is implicitly known as MyBase in VB.Net
The following program demonstrates this:
' Base class
Class Rectangle
   Protected width As Double
   Protected length As Double
   Public Sub New(ByVal l As Double, ByVal w As Double)
      length = l
      width = w
   End Sub
   Public Function GetArea() As Double
      Return (width * length)
   End Function
   Public Overridable Sub Display()
      Console.WriteLine("Length: {0}", length)
      Console.WriteLine("Width: {0}", width)
      Console.WriteLine("Area: {0}", GetArea())
   End Sub
   'end class Rectangle  
End Class
'Derived class
Class Tabletop : Inherits Rectangle
   Private cost As Double
   Public Sub New(ByVal l As Double, ByVal w As Double)
      MyBase.New(l, w)
   End Sub
   Public Function GetCost() As Double
      Dim cost As Double
      cost = GetArea() * 70
      Return cost
   End Function
   Public Overrides Sub Display()
      MyBase.Display()
      Console.WriteLine("Cost: {0}", GetCost())
   End Sub
    'end class Tabletop
End Class
Class RectangleTester
   Shared Sub Main()
      Dim t As Tabletop = New Tabletop(4.5, 7.5)
      t.Display()
      Console.ReadKey()
   End Sub
End Class
When the above code is compiled and executed, it produces following result:
Length: 4.5
Width: 7.5
Area: 33.75
Cost: 2362.5
VB.Net supports multiple inheritance.

VB.Net - Exception Handling


An exception is a problem that arises during the execution of a program. An exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero.
Exceptions provide a way to transfer control from one part of a program to another. VB.Net exception handling is built upon four keywords: TryCatchFinally and Throw.
  • Try: A Try block identifies a block of code for which particular exceptions will be activated. It's followed by one or more Catch blocks.
  • Catch: A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The Catch keyword indicates the catching of an exception.
  • Finally: The Finally block is used to execute a given set of statements, whether an exception is thrown or not thrown. For example, if you open a file, it must be closed whether an exception is raised or not.
  • Throw: A program throws an exception when a problem shows up. This is done using a Throw keyword.

Syntax

Assuming a block will raise and 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
You can list down multiple catch statements to catch different type of exceptions in case your try block raises more than one exception in different situations.

Exception Classes in .Net Framework

In the .Net Framework exceptions are represented by classes. The exception classes in .Net Framework are mainly directly or indirectly derived from the System.Exception class. Some of the exception classes derived from the System.Exception class are the System.ApplicationException andSystem.SystemException classes.
The System.ApplicationException class supports exceptions generated by application programs. So the exceptions defined by the programmers should derive from this class.
The System.SystemException class is the base class for all predefined system exception.
The following table provides some of the predefined exception classes derived from the Sytem.SystemException class:
Exception ClassDescription
System.IO.IOExceptionHandles I/O errors.
System.IndexOutOfRangeExceptionHandles errors generated when a method refers to an array index out of range.
System.ArrayTypeMismatchExceptionHandles errors generated when type is mismatched with the array type.
System.NullReferenceExceptionHandles errors generated from deferencing a null object.
System.DivideByZeroExceptionHandles errors generated from dividing a dividend with zero.
System.InvalidCastExceptionHandles errors generated during typecasting.
System.OutOfMemoryExceptionHandles errors generated from insufficient free memory.
System.StackOverflowExceptionHandles errors generated from stack overflow.

Handling Exceptions

VB.Net provides a structured solution to the exception handling problems in the form of try and catch blocks. Using these blocks the core program statements are separated from the error-handling statements.
These error handling blocks are implemented using the TryCatch and Finally keywords. Following is an example of throwing an exception when dividing by zero condition occurs:
Module exceptionProg
   Sub division(ByVal num1 As Integer, ByVal num2 As Integer)
      Dim result As Integer
      Try
          result = num1 \ num2
      Catch e As DivideByZeroException
          Console.WriteLine("Exception caught: {0}", e)
      Finally
          Console.WriteLine("Result: {0}", result)
      End Try
   End Sub
   Sub Main()
      division(25, 0)
      Console.ReadKey()
  End Sub
End Module
When the above code is compiled and executed, it produces following result:
Exception caught: System.DivideByZeroException: Attempted to divide by zero. 
at ...
Result: 0

Creating User-Defined Exceptions

You can also define your own exception. User defined exception classes are derived from theApplicationException class. The following example demonstrates this:
Module exceptionProg
   Public Class TempIsZeroException : Inherits ApplicationException
      Public Sub New(ByVal message As String)
          MyBase.New(message)
      End Sub
   End Class
   Public Class Temperature
      Dim temperature As Integer = 0
      Sub showTemp()
          If (temperature = 0) Then
              Throw (New TempIsZeroException("Zero Temperature found"))
          Else
              Console.WriteLine("Temperature: {0}", temperature)
          End If
      End Sub
   End Class
   Sub Main()
      Dim temp As Temperature = New Temperature()
      Try
          temp.showTemp()
      Catch e As TempIsZeroException
          Console.WriteLine("TempIsZeroException: {0}", e.Message)
      End Try
      Console.ReadKey()
   End Sub
End Module
When the above code is compiled and executed, it produces following result:
TempIsZeroException: Zero Temperature found

Throwing Objects

You can throw an object if it is either directly or indirectly derived from the System.Exception class.
You can use a throw statement in the catch block to throw the present object as:
Throw [ expression ]
The following program demonstrates this:
Module exceptionProg
   Sub Main()
      Try
          Throw New ApplicationException("A custom exception _
		  is being thrown here...")
      Catch e As Exception
          Console.WriteLine(e.Message)
      Finally
          Console.WriteLine("Now inside the Finally Block")
      End Try
      Console.ReadKey()
   End Sub
End Module
When the above code is compiled and executed, it produces following result:
A custom exception is being thrown here...
Now inside the Finally Block

VB.Net - Dialog Boxes

There are many built-in dialog boxes to be used in Windows forms for various tasks like opening and saving files, printing a page, providing choices for colors, fonts, page set up etc. to the user of an application. These built-in dialog boxes reduce the developer's time and work load.
All of these dialog box control classes inherit from the CommonDialog class and override theRunDialog() function of the base class to create the specific dialog box.
The RunDialog() function is automatically invoked when a user of a dialog box calls its ShowDialog()function.
The ShowDialog method is used to display all the dialog box controls at run time. It returns a value of the type of DialogResult enumeration. The values of DialogResult enumeration are:
  • Abort - returns DialogResult.Abort value, when user clicks an Abort button.
  • Cancel- returns DialogResult.Cancel, when user clicks a Cancel button.
  • Ignore - returns DialogResult.Ignore, when user clicks an Ignore button.
  • No - returns DialogResult.No, when user clicks a No button.
  • None - returns nothing and the dialog box continues running.
  • OK - returns DialogResult.OK, when user clicks an OK button
  • Retry - returns DialogResult.Retry , when user clicks an Retry button
  • Yes - returns DialogResult.Yes, when user clicks an Yes button
The following diagram shows the common dialog class inheritance:
VB.Net Dialog Boxes
All these above mentioned classes have corresponding controls that could be added from the Toolbox during design time. You can include relevant functionality of these classes to your application, either by instantiating the class programmatically or by using relevant controls.
When you double click any of the dialog controls in the toolbox or drag the control onto the form, it appears in the Component tray at the bottom of the Windows Forms Designer, they do not directly show up on the form.
The following table lists the commonly used dialog box controls. Click the following links to check their detail:
S.N.Control & Description
1ColorDialog
It represents a common dialog box that displays available colors along with controls that enable the user to define custom colors.
2FontDialog
It prompts the user to choose a font from among those installed on the local computer and lets the user select the font, font size, and color.
3OpenFileDialog
It prompts the user to open a file and allows the user to select a file to open.
4SaveFileDialog
It prompts the user to select a location for saving a file and allows the user to specify the name of the file to save data.
5PrintDialog
It lets the user to print documents by selecting a printer and choosing which sections of the document to print from a Windows Forms application.


No comments:

Post a Comment