114
http: //www.tut o ri alspoint. co m/vb.net/vb.net_qui ck_g ui de.htm Copyright © tutorialspoint.com  VB. NET - QUICK GUIDE  VB. NET - OVERVIEW  Visual Basic .NET (VB .NE T ) is an obj e ct-o ri e n ted co m pu ter prog ram m i n g l an g u ag e im pl e m e n ted on th e .N ET Fr am e work. Al thoug h i t is an evo lu ti on of clas s ic Vi s ual Bas ic lang uage , it i s n ot bac kwards -compatible with VB6, and any code written in the old version does not compile under VB.NET. Lik e all oth e r .NET lang u ag e s , VB .NE T has co m pl e te support for obj e ct-or i e n ted conce pts. Eve ryth in g i n  VB.NET i s an obj e ct, i n clu di n g al l of t h e prim i ti ve types (Sh ort, In teg er, Long , Stri n g , Boolean, e tc.) an d u se r- defined types, events, and even assemblies. All objects inherits from the base class Object.  VB.NET i s im pl e m e n ted of Mi cro s oft 's .NE T fram e work. There fore , i t h as fu ll acce s s to al l th e li braries in th e .Ne t Framework. It 's also pos s i ble to ru n VB.NET prog ram s o n Mon o, th e ope n-s ource alt e rn ati ve to .NE T , n ot onl y un de r Win dows , but eve n Lin ux or Mac OSX. T h e fol low i n g re aso n s m ake VB.Ne t a w i de l y use d profe ss i onal l an g u ag e: Modern, ge ne ral pu rpose . Obje ct ori e n t e d. Component oriented. Eas y to l e arn . Stru ctu re d lan g u ag e. It produce s eff i cient prog rams. It ca n be co m pil e d on a variety o f co m put e r platf orms. Part of .Ne t Fram e work. Strong Prog ramming Fe atures VB.Net  VB.Net has numerous s tron g prog ramm i n g featu res that m ake i t e n de ari n g to mu l ti tu de o f prog ram m ers  world wi de . Le t u s men ti on so m e o f th e s e fe atu re s: Boolean Conditions  Au tom ati c Garbag e C oll e cti on Stan dard L i brar y  Ass em bly Vers i oni n g Prope rti es and Even ts De l eg ates an d Eve n ts Man ag e m ent Easy-to-use Generics Indexers Conditional Compilation Simple Mult ith re ading  VB. NET - ENVIRONMENT Inte g rated Develo pment Environ ment (I DE) For VB. Net http://www.tutorialspoint.com/more.htm

Vb.net Quick Guide

Embed Size (px)

Citation preview

  • 5/28/2018 Vb.net Quick Guide

    1/114

    http://www.tuto rialspoint.co m/vb.net/vb.net_quick_guide.htm Copyright tutorialspoint.com

    VB.NET - QUICK GUIDE

    VB.NET - OVERVIEW

    Visual Basic .NET (VB.NET) is an object-oriented computer prog ramming lang uag e implemented on the .NETFramework. Although it is an evolution of classic Visual Basic lang uage, 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 lang uag es, VB.NET has complete support for object-oriented concepts. Eve rything inVB.NET is an object, including all of the primitive types (Short, Integ er, Long, String , Boolean, etc.) and use r-defined types, events, and even assemblies. All objects inherits from the base class Object.

    VB.NET is implemented of Microsoft's .NE T framework. There fore, it has full access to all the libraries in the.Net Framework. It's also possible to run VB.NET prog rams on Mono, the open-source alternative to .NET, notonly under Windows, but eve n Linux or Mac OSX.

    The following reasons make VB.Net a widely used profess ional lang uag e:

    Modern, ge neral purpose .

    Obje ct oriented.

    Component oriented.

    Easy to learn.

    Structured lang uag e.

    It produces efficient prog rams.

    It can be compiled on a variety of computer platforms.

    Part of .Net Framework.

    Strong Prog ramming Features VB.Net

    VB.Net has numerous strong prog ramming features that make it endearing to multitude of prog rammersworldwide. Let us mention some of these features:

    Boolean Conditions

    Automatic Garbag e Collection

    Standard Library

    Assembly Vers ioning

    Prope rties and Events

    Deleg ates and Events Management

    Easy-to-use Generics

    Indexers

    Conditional Compilation

    Simple Multithre ading

    VB.NET - ENVIRONMENT

    Integrated Development Environment (IDE) For VB.Net

    http://www.tutorialspoint.com/more.htm

    http://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htmhttp://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm
  • 5/28/2018 Vb.net Quick Guide

    2/114

    Microsoft provides the following development tools for VB.Net prog ramming :

    Visual Studio 2010 (VS)

    Visual Basic 2010 Expre ss (VBE)

    Visual Web Developer

    The last two are free. Us ing these tools, you can write all kinds of VB.Ne t prog rams from simple command-lineapplications to more complex applications. Visual Basic Expre ss and Visual Web Developer Expre ss edition aretrimmed down versions of Visual Studio and has the same look and feel. They re tain most features of VisualStudio. In this tutorial, we have used Visual Basic 2010 Expre ss and Visual Web Developer (for the webprog ramming chapter).

    You can download it fromhere. It g ets automatically installed in your machine. Please note that you need an activeinternet connection for installing the expre ss edition.

    Writing VB.Net Programs on Linux or Mac OS

    Although the.NET Framework runs on the Windows ope rating system, there are some alternative ve rsions thatwork on other operating systems. Mono is an open-source ve rsion of the .NET Framework which includes aVisual 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 tobring better deve lopment tools to Linux deve lopers. Mono can be run on many operating systems includingAndroid, BSD, iOS, Linux, OS X, Windows, Solaris and UNIX.

    VB.NET - PROGRAM STRUCTURE

    Before we s tudy basic building blocks of the VB.Net prog ramming lang uag e, let us look a bare minimum VB.Netprog ram structure so that we can take it as a re fere nce in upcoming chapters.

    VB.Net Hello World ExampleA VB.Net prog ram basically consists of the following parts:

    Namespace declaration

    A class or module

    One or more procedures

    Variables

    The Main procedure

    Statements & Express ions

    Comments

    Le t us look at a simple code that would print the words "Hello World":

    ImportsSystemModuleModule1 'This program will display Hello World

    Sub Main() Console.WriteLine("Hello World") Console.ReadKey()

    End SubEnd Module

    When the above code is compiled and exe cuted, it produces the following result:

    Hello, World!

    http://www.microsoft.com/visualstudio/eng/downloads
  • 5/28/2018 Vb.net Quick Guide

    3/114

    Let us look various parts of the above prog ram:

    The first line of the prog ram Imports Systemis used to include the System namespace in the prog ram.

    The next line has a Modulede claration, the moduleModule1. VB.Net is completely object oriented, soevery prog ram must contain a module of a class that contains the data and procedures that your prog ramuses.

    Class es or Modules g enerally 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 thefollowing :

    Function

    Sub

    Operator

    Get

    Set

    AddHandler

    RemoveHandler

    RaiseEvent

    The next line( 'This prog ram) will be ig nored by the compiler and it has been put to add additionalcomments in the prog ram.

    The next line defines the Main proce dure, which is the entry point for all VB.Net prog rams. T he Mainprocedure states what the module or c lass will do when executed.

    The Main procedure specifies its behavior with the statement

    Console.WriteLine("Hello World")

    WriteLineis a method of the Consoleclass defined in theSystemnamespace . T his statement causes themes sag e "Hello, World!" to be displayed on the scree n.

    The last line Console.ReadKey() is for the VS.NET Users. This will prevent the screen from runningand closing quickly when the prog ram is launched from Visual Studio .NET.

    Compile & Execute VB.Net Program:

    If you are using Visual Studio.Ne t 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 Explore r.

    Write code in the C ode Editor.

    Click the Run button or the F5 key to run the project. A Command Prompt window appears that containsthe line Hello World.

    VB.NET - BASIC SYNTAX

  • 5/28/2018 Vb.net Quick Guide

    4/114

    VB.Net is an object oriented prog ramming lang uag e. In Object Oriented Prog ramming methodolog y, aprog ram consists of various objects that interact with each other by means of actions. T he actions that an objectmay take are called methods. Obj ects 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 prog ram it can be de fined as a collection of obje cts that communicate via invokingeach 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 s tates - color, name, bree d as well asbehaviors - wagg ing , barking , eating , etc. An object is an instance of a class.

    Class- A class can be defined as a template/blueprint that describe the behaviors/states that object of itstype support.

    Methods- A method is basically a behavior. A c lass can contain many methods . It is in methods where thelogics are written, data is manipulated and all the actions are executed.

    Instant Variables- Each obje ct has its unique set of instant variables. An object's s tate is cre ated bythe values assigned to these instant variables.

    A Rectangle Clas s in VB.Net

    For example, let us consider a Re ctangle object. It has attributes like leng th and width. De pending upon thedesig n, it may need ways for acce pting the values of these attributes, calculating area and display de tails.

    Le t us look at an implementation of a Rectangle class and discuss VB.Net basic syntax, on the basis of ourobs ervations in it:

    ImportsSystemPublicClassRectangle Privatelength AsDouble Privatewidth AsDouble

    '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 SubEnd Class

    When the above code is compiled and exe cuted, it produces the following result:

    Length: 4.5

    Width: 3.5Area: 15.75

    In previous chapter, we created a Visual Basic module that held the code. Sub Main indicates the entry point ofVB.Net prog ram. Here , we are using Class that contains both code and data. You use classe s to cre ate objects.For example, in the code , r is a Rectang le obje ct.

  • 5/28/2018 Vb.net Quick Guide

    5/114

    An object is an instance of a class :

    Dimr AsNewRectangle()

    A class may have members that can be acce ssible from outside class, if so s pecified. Data members are calledfields and procedure members are called methods.

    Sharedmethods or static methods can be invoked without creating an obj ect of the class. Instance methods

    are invoked through an object of the class:

    SharedSubMain() Dimr AsNewRectangle() r.Acceptdetails() r.Display() Console.ReadLine()EndSub

    Identifiers

    An identifier is a name use d to identify a class, variable, function, or any other user-de fined item. The bas ic rulesfor naming classes in VB.Net are as follows:

    A name must beg in with a letter that could be followed by a sequence of letters, dig its (0 - 9) orunderscore . The first character in an identifier cannot be a digit.

    It must not contain any embedded space or symbol like ? - +! @ # % ^ & * ( ) [ ] { } . ; : " ' / and \. Howeveran underscore ( _ ) can be used.

    It should not be a re served keyword.

    VB.Net Keywords

    The following table lists the VB.Net reserved keywords:

    AddHandler AddressOf Alias And AndAlso As Boolean

    ByRef Byte ByVal Call Case Catch CBool

    CByte CChar CDate CDec CDbl Char CInt

    Class CLng CObj Const Continue CSByte CShort

    CSng CStr CType CUInt CULng CUShort Date

    Decimal Declare Default Deleg ate Dim DirectCast Do

    Double Each Else ElseIf End End If Enum

    Erase Error Event Exit False Finally For

    Friend Function Get GetType GetXMLNamespace

    Global GoTo

    Handles If Implements Imports In Inherits Integ er

    Interface Is IsNot Let Lib Like Long

    Loop Me Mod Module MustInherit MustOverride MyBase

    MyClass Namespace Narrowing New Next Not Nothing

    NotInheritable

    NotOverridable

    Object Of On Operator Option

  • 5/28/2018 Vb.net Quick Guide

    6/114

    Optional Or OrElse Overloads Overridable Overrides ParamArray

    Partial Private Property Protected Public RaiseEvent ReadOnly

    ReDim REM RemoveHandler

    Resume Return SByte Select

    Set Shadows Shared Short Sing le Static Step

    Stop String Structure Sub SyncLock Then Throw

    To True Try TryCast TypeOf UInteg er While

    Widening With WithEve nts WriteOnly Xor

    VB.NET - DATA TYPES

    Data types refer to an extensive system use d for declaring variables or functions of different types. The type of avariable de termines how much space it occupies in storag e and how the bit pattern stored is interpre ted.

    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 T ype Storag eAllocation

    Value Rang e

    Boolean Depends onimplementingplatform

    Trueor False

    Byte 1 byte 0 throug h 255 (unsig ned)

    Char 2 bytes 0 throug h 65535 (unsig ned)

    Date 8 bytes 0:00:00 (midnig ht) on January 1, 0001 throug h 11:59:59 PM onDecember 31, 9999

    Decimal 16 bytes 0 throug h +/-79,228,162,514,264,337,593,543,950,335 (+/-7.9...E+28)with no decimal point; 0 throug h +/-7.9228162514264337593543950335 with 28 places to the right ofthe decimal

    Double 8 bytes -1.79769313486231570E+308 throug h -4.94065645841246544E-324, for neg ative values

    4.94065645841246544E-324 throug h1.79769313486231570E+308, for pos itive values

    Integ er 4 bytes -2,147,483,648 throug h 2,147,483,647 (sig ned)

    Long 8 bytes -9,223,372,036,854,775,808 throug h9,223,372,036,854,775,807(signed)

    Object 4 bytes on 32-bitplatform

    8 bytes on 64-bitplatform

    Any type can be s tored in a variable of type Obje ct

  • 5/28/2018 Vb.net Quick Guide

    7/114

    SByte 1 byte -128 throug h 127 (sig ned)

    Short 2 bytes -32,768 throug h 32,767 (sig ned)

    Sing le 4 bytes -3.4028235E+38 throug h -1.401298E-45 for neg ative values;

    1.401298E-45 through 3.4028235E+38 for positive values

    String Depends onimplementingplatform

    0 to approximately 2 billion Unicode characters

    UInteg er 4 bytes 0 throug h 4,294,967,295 (unsig ned)

    ULong 8 bytes 0 throug h 18,446,744,073,709,551,615 (unsig ned)

    User-Defined

    Depends onimplementingplatform

    Each member of the structure has a range determined by its data typeand independent of the ranges of the other members

    UShort 2 bytes 0 throug h 65,535 (unsig ned)

    Example

    The following example demonstrates use of some of the types:

    ModuleDataTypes SubMain() Dimb AsByte Dimn AsInteger Dimsi AsSingle Dimd AsDouble

    Dimda AsDate Dimc AsChar Dims AsString Dimbl AsBoolean b =1 n =1234567 si =0.12345678901234566 d =0.12345678901234566 da =Today c ="U"c s ="Me" IfScriptEngine="VB"Then bl =True Else

    bl =False EndIf Ifbl 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 exe cuted, it produces the following result:

    U and, Medeclaring on the day of: 12/4/2012 12:00:00 PMWe will learn VB.Net seriously

  • 5/28/2018 Vb.net Quick Guide

    8/114

    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.N Functionss & Description

    1 CBool(expression)Converts the expression to Boolean data type.

    2 CByte(expression)Converts the expression to Byte data type.

    3 CChar(expression)Converts the expression to Char data type.

    4 CDate(expression)Converts the expression to Date data type

    5 CDbl(expression)Converts the expression to Double data type.

    6 CDec(expression)Converts the expression to Decimal data type.

    7 CInt(expression)Converts the expression to Integer data type.

    8 CLng(expression)Converts the expression to Long data type.

    9 CObj(expression)Converts the express ion to Obj ect type.

    10 CSByte(expression)Converts the expression to SByte data type.

    11 CShort(expression)Converts the expression to Short data type.

    12 CSng(expression)Converts the expression to Sing le data type.

    13 CStr(expression)Converts the expression to String data type.

    14 CUInt(expression)Converts the expression to UInt data type.

    15 CULng(expression)Converts the e xpression to ULng data type.

    16 CUShort(expression)Converts the expression to UShort data type.

    Example:

    The following example de monstrates some of these functions:

    ModuleDataTypes

  • 5/28/2018 Vb.net Quick Guide

    9/114

    SubMain() Dimn AsInteger Dimda AsDate Dimbl AsBoolean=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() EndSubEndModule

    When the above code is compiled and exe cuted, it produces the following result:

    True-1True12/4/20121

    1

    VB.NET - VARIABLES

    A variable is nothing but a name g iven to a storage are a that our prog rams can manipulate. Each variable inVB.Net has a specific type, which determines the s ize and layout of the variable's memory; the range of valuesthat can be stored within that memory; and the set of ope rations that can be applied to the variable.

    We have already discussed various data types. T he bas ic value types provided in VB.Net can be categ orized as:

    Type Example

    Integral types SByte, Byte, Short, UShort, Integer, UInteger, Long, ULong and Char

    Floating point types Single and Double

    Decimal types Decimal

    Boolean types True or False values, as assig ned

    Date types Date

    VB.Net also allows defining other value types of variable like Enumand reference types of variables like Class.We will discuss date types and Class es, in subsequent chapters.

    Variable Declaration in VB.Net

    The Dimstatement is used for variable declaration and storage allocation for one or more variables. T he Dimstatement is used at module, class , structure, procedure or block leve l.

    Syntax for variable declaration in VB.Net is:

    [][accessmodifier ][[Shared][Shadows]|[Static]][ReadOnly]Dim[WithEvents]variablelist

    Where,

    attributelistis a list of attributes that apply to the variable. Optional.

    accessmodifierdefines the access levels of the variables, it has values as - Public, Protected, Friend,Protected Friend and Private. Optional.

  • 5/28/2018 Vb.net Quick Guide

    10/114

    Shareddeclares a shared variable, which is not ass ociated with any specific instance of a class orstructure, rather available to all the instances of the class or structure. Optional.

    Shadowsindicate that the variable re-declares and hides an identically named element, or set ofoverloaded e lements, in a base class . Optional.

    Staticindicates that the variable will retain its value, even when the after termination of the procedure inwhich it is declared. Optional.

    ReadOnlymeans the variable can be read, but not written. Optional.

    WithEventsspecifies that the variable is used to respond to eve nts raised by the instance assigned tothe variable. Optional.

    Variablelistprovides 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 spe cifies the data type of the variable.

    initializer: Optional if New is not specified. Expre ssion that is evaluated and assigned to the variablewhen it is created.

    Some valid variable declarations along with their definition are shown here:

    DimStudentIDAsIntegerDimStudentNameAsStringDimSalaryAsDoubleDimcount1,count2 AsIntegerDimstatus AsBooleanDimexitButton AsNewSystem.Windows.Forms.ButtonDimlastTime,nextTime AsDate

    Variable Initialization in VB.Net

    Variables are initialize d (assig ned a value) with an equal sig n followed by a constant expression. The g eneral

    form of initialization is:

    variable_name =value;

    for example,

    Dimpi AsDoublepi =3.14159

    You can initialize a variable at the time of declaration as follows:

    DimStudentIDAsInteger=100DimStudentNameAsString="Bill Smith"

    Example

    Try the following example, which makes use of various types of variables:

  • 5/28/2018 Vb.net Quick Guide

    11/114

    ModulevariablesNdataypes SubMain() Dima AsShort Dimb AsInteger Dimc AsDouble a =10 b =20 c =a +b Console.WriteLine("a = {0}, b = {1}, c = {2}",a,b,c) Console.ReadLine()

    EndSubEndModule

    When the above code is compiled and exe cuted, it produces the following result:

    a = 10, b = 20, c = 30

    Accepting Values from User

    The Console c lass in the System namespace provides a function ReadLinefor acce pting input from the userand store it into a variable. For example,

    Dimmessage AsStringmessage =Console.ReadLine

    The following example demonstrates it:

    ModulevariablesNdataypes SubMain() Dimmessage AsString Console.Write("Enter message: ") message =Console.ReadLine Console.WriteLine() Console.WriteLine("Your Message: {0}",message)

    Console.ReadLine() EndSubEndModule

    When the above code is compiled and exe cuted, it produces the following result (assume the use r inputs HelloWorld):

    Enter message: Hello WorldYour Message: Hello World

    VB.NET - CONSTANTS AND ENUMERATIONS

    The constantsre fer to fixed values that the prog ram may not alter during its e xecution. These fixed values arealso called literals.

    Constants can be of any of the basic data types like an integ er constant, a floating constant, a character constant,or a string literal. There are also e numeration constants as well.

    The constants are treated just like reg ular variables exce pt that their values cannot be modified after theirde finition.

    Anenumerationis a set of named integ er constants.

    Declaring Constants

    In VB.Net, constants are declared using the Conststatement. 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:

    [][accessmodifier ][Shadows]

  • 5/28/2018 Vb.net Quick Guide

    12/114

    Constconstantlist

    Where,

    attributelist: specifies the list of attributes applied to the constants; you can provide multiple attributes ,se parated by commas. Optional.

    accessmodifier: spe cifies which code can acce ss these constants. Optional. Values can be e ither of the:Public, Protected, Friend, Protected Friend, or Private.

    Shadows: this makes the constant hide a prog ramming 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 [Asdatatype ]=initializer

    constantname: specifies the name of the constant

    datatype: spe cifies the data type of the constant

    initializer: spe cifies the value ass ig ned to the constant

    For example,

    ' The following statements declare constants.Const maxval As Long = 4999Public Const message As String = "HELLO"Private Const piValue As Double = 3.1415

    Example

    The following example de monstrates de claration and use of a constant value:

    ModuleconstantsNenum SubMain() ConstPI =3.14149 Dimradius,area AsSingle radius =7 area =PI *radius *radius Console.WriteLine("Area = "&Str(area)) Console.ReadKey() EndSubEndModule

    When the above code is compiled and exe cuted, it produces the following result:

    Area = 153.933

    Print and Display Constants in VB.Net

    VB.Net provides the following print and display constants:

    Constant Description

    vbCrLf Carriag e re turn/linefeed character combination.

    vbCr Carriag e re turn character.

    vbLf Linefee d character.

  • 5/28/2018 Vb.net Quick Guide

    13/114

    vbNewLine Newline character.

    vbNullChar Null character.

    vbNullString Not the same as a zero-leng th string (""); used for calling external procedures.

    vbObjectError Error number. User-de fined error numbers should be g reater than this value.For example:Err.Raise (Number) = vbObjectError + 1000

    vbTab Tab character.

    vbBack Backspace character.

    Declaring Enumerations

    An enumerated type is declared using the Enumstatement. The Enum statement declare s an enumeration anddefines the values of its members. T he Enum statement can be used at the module, class, structure, proce dure,or block level.

    The syntax for the Enum statement is as follows:

    [][accessmodifier ] [Shadows]Enumenumerationname [Asdatatype ]

    memberlistEndEnum

    Where,

    attributelist: refers to the list of attributes applied to the variable. Optional.

    asscessmodifier: spe cifies which code can acce ss these enumerations. Optional. Values can be either ofthe: Public, Protected, Friend or Private.

    Shadows: this makes the enumeration hide a prog ramming 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: spe cifies the list of member constants being declared in this s tatement. Required.

    Each member in the memberlist has the following syntax and parts:

    []member name [=initializer ]

    Where,

    name: specifies the name of the member. Re quired.

    initializer: value assigned to the enumeration member. Optional.

    For example,

    EnumColors red =1 orange =2 yellow =3 green =4 azure =5 blue =6 violet =7EndEnum

  • 5/28/2018 Vb.net Quick Guide

    14/114

    Example

    The following example de monstrates declaration and use of the Enum variable Colors:

    ModuleconstantsNenum EnumColors red =1 orange =2 yellow =3

    green =4 azure =5 blue =6 violet =7 EndEnum SubMain() 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() EndSubEndModule

    When the above code is compiled and exe cuted, it produces the following result:

    The Color Red is: 1The Color Yellow is: 3The Color Blue is: 6The Color Green is: 4

    VB.NET - MODIFIERS

    The modifiers are keywords added with any prog ramming element to g ive some e special emphasis on how theprog ramming element will behave, or will be accesse d in the prog ram

    For example, the access modifiers: Public, Private, Protected, Friend, Protected Friend, etc., indicates theaccess level of a prog ramming element like a variable, constant, enumeration or a c lass.

    List of Available Modifiers in VB.Net

    The following table provides the complete list of VB.Net modifiers:

    S.N Modifier Description

    1 Ansi Specifies that Visual Basic should marshal all string s to American NationalStandards Institute (ANSI) values reg ardless of the name of the e xternal

    procedure being declared.

    2 Ass embly Spe cifie s that an attribute at the be g inning of a s ource file applie s to theentire ass embly.

    3 Async Indicates that the method or lambda expression that it modifies isasynchronous. Such methods are referre d to as async methods. Thecaller of an async method can resume its work without waiting for theasync method to finish..

    4 Auto The charsetmodifierpart in the Declarestatement supplies thecharacter set information for marshaling string s during a call to the

    external procedure. It also affects how Visual Basic searches the externalfile for the external procedure name. The Auto modifier specifies that

    Visual Basic should marshal string s according to .NET Framework rules.

    5 ByRef Specifies that an arg ument is passed by reference, i.e., the calledproce dure can chang e the value of a variable underlying the arg ument in

  • 5/28/2018 Vb.net Quick Guide

    15/114

    the calling code. It is used under the contexts of:

    Declare Statement

    Function Statement

    Sub Statement

    6 ByVal Specifies that an arg ument is passed in such a way that the called

    proce dure or property cannot chang e the value of a variable underlyingthe arg ument in the calling code. It is used under the contexts of:

    Declare Statement

    unction Statement

    Operator Statement

    Property Statement

    Sub Statement

    7 Default Identifies a property as the default property of its class, structure, orinterface.

    8 Friend Specifies that one or more declared prog ramming elements areaccessible from within the assembly that contains their declaration, notonly by the component that declares them.Friendaccess is often the preferre d level for an application'sprog ramming elements, and Friend is the default access level of aninterface , a module, a c lass, or a structure.

    9 In It is used in g eneric interfaces and deleg ates.

    10 Iterator Specifies that a function or Get accessor is an iterator. An iteratorperforms a custom iteration over a collection.

    11 Key The Key keyword enables you to specify behavior for properties of anonymous types.

    12 Module Spe cifies that an attribute at the be ginning of a source file applies to thecurrent assembly module. It is not same as the Module statement.

    13 MustInhe rit Spe cifie s that a class can be used only as a base class and that you cannotcre ate an obje ct directly from it.

    14 MustOverride Specifies that a property or procedure is not implemented in this class and

    must be overridden in a derived class before it can be used.

    15 Narrowing Indicates that a conversion operator (CT ype) converts a class orstructure to a type that might not be able to hold some of the possible

    values of the original class or structure.

    16 NotInhe ritable Spe cifie s that a clas s cannot be use d as a base clas s.

    17 NotOverridable Specifies that a property or procedure cannot be overridden in a derivedclass.

    18 Optional Spe cifies that a procedure arg ument can be omitted whe n the procedure

    is called.

    19 Out For g eneric type parameters, the Out keyword specifies that the type iscovariant.

    20 Ove rloads Spe cifies that a property or procedure re de clares one or more existing

  • 5/28/2018 Vb.net Quick Guide

    16/114

    properties or proce dures with the same name.

    21 Ove rridable Spe cifie s that a prope rty or proce dure can be ove rridde n by an ide ntically named property or procedure in a derived class.

    22 Ove rride s Spe cifie s that a prope rty or proce dure ove rride s an ide ntically name dproperty or procedure inherited from a base class.

    23 ParamArray ParamArray allows you to pass an arbitrary numbe r of arg ume nts to the

    procedure. A ParamArray parameter is always declared using ByVal.

    24 Partial Indicate s that a clas s or s tructure de claration is a partial de finition of theclass or s tructure.

    25 Private Specifies that one or more declared prog ramming elements areaccessible only from within their declaration context, including from withinany contained types.

    26 Protected Specifies that one or more declared prog ramming elements areaccessible only from within their own class or from a derived class.

    27 Public Specifies that one or more declared prog ramming elements have no

    access restrictions.

    28 Re adOnly Spe cifies that a variable or prope rty can be read but not writte n.

    29 Shadows Spe cifies that a declare d prog ramming ele ment redeclare s and hide s anidentically named element, or set of overloaded e lements, in a base class.

    30 Shared Specifies that one or more declared prog ramming elements areassociated with a class or structure at larg e, and not with a specificinstance of the class or structure.

    31 Static Specifies that one or more declared local variables are to continue to exist

    and retain their latest values after termination of the proce dure in whichthey are de clared.

    32 Unicode Spe cifie s that Visual Bas ic s hould mars hal all s tring s to Unicode value sreg ardless of the name of the external proce dure being declared.

    33 Widening Indicates that a conversion operator (CT ype) converts a class orstructure to a type that can hold all possible values of the orig inal class orstructure.

    34 WithEve nts Spe cifies that one or more de clared me mber variable s re fer to aninstance of a class that can raise events.

    35 WriteOnly Specifies that a property can be written but not read.

    VB.NET - STATEMENTS

    A statementis a complete instruction in Visual Basic prog rams. It may contain keywords, ope rators , variables ,literal values, constants and expre ssions.

    Statements could be categ orize d as:

    Declaration statements- these are the statements where you name a variable, constant, orprocedure, and can also specify a data type.

    Executable statements- these are the statements, which initiate actions. These statements can call amethod or function, loop or branch through blocks of code or as sign values or e xpression to a variable orconstant. In the last case, it is called an Assig nment statement.

  • 5/28/2018 Vb.net Quick Guide

    17/114

    Declaration Statements

    The declaration statements are used to name and define procedures, variables, prope rties, arrays, andconstants. When you declare a prog ramming element, you can also de fine its data type, access level, and scope.

    The prog ramming elements you may declare include variables, constants, e numerations, classe s, 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.N Statements and Description Example

    1 Dim StatementDeclares and allocates storag e space for one ormore variables.

    Dim number As IntegerDim quantity As Integer = 100Dim message As String = "Hello!"

    2 Const StatementDeclares and defines one or more constants. Const maximum As Long = 1000

    Const naturalLogBase As Object= CDec(2.7182818284)

    3 Enum StatementDeclares an enumeration and defines the values of itsmembers.

    Enum CoffeeMugSize Jumbo ExtraLarge Large Medium SmallEnd Enum

    4 Class StatementDe clares the name of a class and introduce s thedefinition of the variables, properties, events, andproce dures that the class comprise s.

    Class BoxPublic length As DoublePublic breadth As DoublePublic height As DoubleEnd Class

    5 Structure StatementDeclares the name of a structure and introduces thedefinition of the variables, properties, events, andprocedures that the structure comprises.

    Structure BoxPublic length As Double

    Public breadth As DoublePublic height As DoubleEnd Structure

    6 Module StatementDeclares the name of a module and introduces thedefinition of the variables, properties, events, andprocedures that the module comprises.

    Public Module myModuleSub Main()Dim user As String =InputBox("What is your name?")MsgBox("User name is" & user)End Sub

    End Module

    7 Interface StatementDeclares the name of an interface and introduces thedefinitions of the members that the interface

    Public Interface MyInterface Sub doSomething()

  • 5/28/2018 Vb.net Quick Guide

    18/114

    comprises. End Interface

    8 Function StatementDe clares the name, parameters, and code that definea Function procedure.

    Function myFunction(ByVal n As Integer) As Double

    Return 5.87 * nEnd Function

    9 Sub StatementDe clares the name, parameters, and code that definea Sub proce dure.

    Sub mySub(ByVal s As String) ReturnEnd Sub

    10 Dec lare StatementDeclares a reference to a procedure implemented inan external file.

    Declare Function getUserNameLib "advapi32.dll"Alias "GetUserNameA"( ByVal lpBuffer As String,

    ByRef nSize As Integer) AsInteger

    11 Operator StatementDeclares the operator symbol, ope rands, and codethat define an operator procedure on a class orstructure.

    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

    12 Property StatementDe clares the name of a property, and the propertyproce dures use d to store and retrieve the value ofthe property.

    ReadOnly Property quote() AsString

    GetReturn quoteString

    End GetEnd Property

    13 Event StatementDeclares a use r-defined eve nt. Public Event Finished()

    14 Deleg ate StatementUse d to declare a deleg ate. Delegate Function MathOperator(

    ByVal x As Double,ByVal y As Double

    ) As Double

    Executable Statements

    An executable statement performs an action. Statements calling a proce dure, branching to another place in thecode, looping through several statements, or evaluating an expression are executable statements. Anass ig nment statement is a special case of an executable s tatement.

    Example

    The following example de monstrates a de cision making statement:

  • 5/28/2018 Vb.net Quick Guide

    19/114

    Moduledecisions SubMain() 'local variable definition ' Dima AsInteger=10

    ' check the boolean condition using if statement ' If(a

  • 5/28/2018 Vb.net Quick Guide

    20/114

    Modulemydirectives#Const age = TrueSubMain() #If age Then Console.WriteLine("You are welcome to the Robotics Club") #End If Console.ReadKey()EndSubEndModule

    When the above code is compiled and exe cuted, it produces the following result:

    You are welcome to the Robotics Club

    The #ExternalSource Directive

    This directive is use d for indicating a mapping between specific lines of source code and text e xternal to thesource . It is used only by the compiler and the debug g er, has no effect on code compilation.

    This directive allows including external code from an external code file into a source code file.

    Syntax for this directive is:

    #ExternalSource( StringLiteral , IntLiteral ) [LogicalLine]#End ExternalSource

    The parameters of #ExternalSource directive are the path of external file, line number of the first line, and theline where the error occurred.

    Example

    The following code demonstrates a hypothetical use of the directive:

    Modulemydirectives PublicClassExternalSourceTester

    SubTestExternalSource()

    #ExternalSource("c:\vbprogs\directives.vb", 5) Console.WriteLine("This is External Code. ") #End ExternalSource

    EndSub EndClass

    SubMain()

    Dimt AsNewExternalSourceTester() t.TestExternalSource() Console.WriteLine("In Main.") Console.ReadKey()

    EndSub

    When the above code is compiled and exe cuted, it produces the following result:

    This is External Code.In Main.

    Th e #If...Then...#Else DirectivesThis directive conditionally compiles selected blocks of Visual Basic code.

    Syntax for this directive is:

  • 5/28/2018 Vb.net Quick Guide

    21/114

    #If expression Then statements[#ElseIf expression Then [statements ]...#ElseIf expression Then [statements ]][#Else [statements ]]#End If

    For example,

    #Const TargetOS = "Linux"#If TargetOS = "Windows 7" Then ' Windows 7 specific code#ElseIf TargetOS = "WinXP" Then 'WindowsXP specific code#Else ' Code for other OS#End if

    Example

    The following code demonstrates a hypothetical use of the directive:

    Modulemydirectives#Const classCode = 8

    SubMain() #If classCode = 7 Then Console.WriteLine("Exam Questions for Class VII") #ElseIf classCode = 8 Then Console.WriteLine("Exam Questions for Class VIII") #Else Console.WriteLine("Exam Questions for Higher Classes")

    #End If Console.ReadKey()

    EndSubEndModule

    When the above code is compiled and exe cuted, it produces the following result:

    Exam Questions for Class VIII

    The #Reg ion Directive

    This directive helps in collapsing and hiding sections of code in Visual Basic files .

    Syntax for this directive is:

    #Region "identifier_string"#End Region

    For example,

    #Region "StatsFunctions"' Insert code for the Statistical functions here.

    #End Region

    VB.NET - OPERATORS

    An operator is a symbol that tells the compiler to perform spe cific mathematical or log ical manipulations. VB.Netis rich in built-in ope rators and provides following types of commonly used ope rators :

  • 5/28/2018 Vb.net Quick Guide

    22/114

    Arithmetic Ope rators

    Comparison Operators

    Logical/Bitwise Operators

    Bit Shift Operators

    Assig nment Operators

    Miscellaneous Operators

    This tutorial will explain the most commonly use d operators .

    Arithmetic Operators

    Following table shows all the arithmetic operators supported by VB.Ne t. Assume variableAholds 2 and variableBholds 7, then:

    Show Examples

    Operator Description Example

    ^ Raises one operand to the power of another B^A will g ive 49

    + Adds two operands A + B will g ive 9

    - Subtracts second operand from the first A - B will g ive -5

    * Multiplies both operands A * B will g ive 14

    / Divide s one ope rand by anothe r and re turns a floatingpoint result

    B / A will give 3.5

    \ Divide s one ope rand by anothe r and re turns an inte g erresult

    B \ A will give 3

    MOD Modulus Operator and remainder of after an integerdivision

    B MOD A will give 1

    Comparison Operators

    Following table shows all the comparison operators supported by VB.Net. Assume variableAholds 10 andvariable Bholds 20, then:

    Show Examples

    Operator Description Example

    = C he cks if the value s of two ope rands are equal or not; if yes, then condition becomes true.

    (A = B) is not true.

    Checks if the values of two operands are equal or not; if values, are not equal then condition becomes true.

    (A B) is true.

    > Checks if the value of le ft operand is greater than the valueof right operand; if yes, then condition becomes true.

    (A > B) is not true.

    < Checks if the value of le ft operand is less than the value of right operand; if yes, then condition becomes true.

    (A < B) is true.

    http://localhost/var/www/apps/conversion/tmp/scratch_6/vb.net/vb.net_comparison_operators.htmhttp://localhost/var/www/apps/conversion/tmp/scratch_6/vb.net/vb.net_arithmetic_operators.htm
  • 5/28/2018 Vb.net Quick Guide

    23/114

    >= Checks if the value of left operand is greater than or equalto the value of right operand; if yes, then condition

    becomes true.

    (A >= B) is not true.

  • 5/28/2018 Vb.net Quick Guide

    24/114

    Bit Shift Operators

    We have already discussed the bitwise operators. T he bit shift operators perform the shift operations on binaryvalues. 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:

    p q p & q p | q p ^ q

    0 0 0 0 0

    0 1 0 1 1

    1 1 1 1 0

    1 0 0 1 1

    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 operatorsare >> and

  • 5/28/2018 Vb.net Quick Guide

    25/114

    operand.

    Assignment Operators

    There are following ass ig nment operators supported by VB.Net:

    Show Examples

    Operator Description Example

    = Simple assig nme nt ope rator, Assig ns value s from rig htside operands to left side operand

    C = A + B will assig n value of A +B into C

    += Add AND assignment operator, It adds right operand tothe left operand and assigns the re sult to left ope rand

    C += A is equivalent to C = C + A

    -= Subtract AND assignment operator, It subtracts rightope rand from the left operand and assig ns the result to leftoperand

    C -= A is equivalent to C = C - A

    *= Multiply AND assignment operator, It multiplies rightope rand with the left operand and assig ns the result to leftoperand

    C *= A is equivalent to C = C * A

    /= Divide AND assignment operator, It divides left operandwith the right operand and assig ns the re sult to leftoperand(floating point division)

    C /= A is equivalent to C = C / A

    \= Divide AND assignment operator, It divides left operandwith the right operand and assig ns the re sult to leftope rand (Integ er division)

    C \= A is equivalent to C = C \A

    ^= Exponentiation and assignment operator. It raises the leftope rand to the power of the rig ht ope rand and ass ig ns theresult to left operand.

    C^=A is equivalent to C = C ^ A

    > 2

    &= Concatenates a String expression to a String variable orprope rty and assig ns the result to the variable orproperty.

    Str1 &= Str2 is same asStr1 = Str1 & Str2

    Miscellaneous Operators

    There are few other important operators supported by VB.Net.

    Show Examples

    Operator Description Example

    AddressOf Returns the addre ss of a procedure.

    AddHandler Button1.Click,AddressOf Button1_Click

    Await It is applied to an operand in an asynchronousmethod or lambda express ion to suspendexecution of the method until the awaited task

    Dim result As res= Await

    http://localhost/var/www/apps/conversion/tmp/scratch_6/vb.net/vb.net_misc_operators.htmhttp://localhost/var/www/apps/conversion/tmp/scratch_6/vb.net/vb.net_assignment_operators.htm
  • 5/28/2018 Vb.net Quick Guide

    26/114

    completes. AsyncMethodThatReturnsResult()

    Await AsyncMethod()

    GetType It returns a Type object for the specifiedtype. The Type object provides informationabout the type such as its properties,methods, and events.

    MsgBox(GetType(Integer).ToString())

    FunctionExpression It declares the parameters and code thatdefine a function lambda e xpression. Dim add5 = Function(num AsInteger) num + 5'prints 10Console.WriteLine(add5(5))

    If It uses short-circuit evaluation to conditionally return one of two values. The If operator can

    be called with three arg uments or with twoarg uments.

    Dim num = 5Console.WriteLine(If(num >= 0,"Positive", "Negative"))

    Operators Precedence in VB.Net

    Operator prece dence determines the g rouping of terms in an express ion. This affects how an express ion isevaluated. C ertain ope rators have hig her prece dence than others; for e xample, the multiplication ope rator hashig her prece dence than the addition operator:

    For e xample, x = 7 + 3 * 2; here, x is assig ned 13, not 20 because operator * has hig her precede nce than +, so itfirst get multiplied with 3*2 and then adds into 7.

    Here , ope rators with the hig hest precedence appear at the top of the table, those with the lowest appear at thebottom. Within an expression, hig her precedence operators will be e valuated first.

    Show Examples

    Operator Precedence

    Await Hig hest

    Exponentiation (^)

    Unary identity and neg ation (+, - )

    Multiplication and floating -point division (*, /)

    Integ er division (\)

    Modulus arithmetic (Mod)

    Addition and subtraction (+, -)

    Arithmetic bit shift ()

    All comparison operators (=, , =, Is, IsNot, Like,TypeOf...Is)

    Neg ation (Not)

    Conjunction (And, AndAlso)

    Inclusive disjunction (Or, OrElse)

    http://localhost/var/www/apps/conversion/tmp/scratch_6/vb.net/vb.net_operators_precedence.htm
  • 5/28/2018 Vb.net Quick Guide

    27/114

    Exclusive disjunction (Xor) Lowest

    VB.NET - DECISION MAKING

    Decision making structures require that the prog rammer specify one or more conditions to be evaluated ortested by the prog ram, along with a statement or statements to be executed if the condition is de termined to betrue, and optionally, other statements to be executed if the condition is determined to be false.

    Following is the g eneral form of a typical decision making structure found in most of the prog ramming lang uages:

    VB.Net provides following types of decision making statements. Click the following links to check their detail.

    Statement Description

    If ... Then statement AnIf...Then statementconsists of a boolean expression followedby one or more statements.

    If...Then...Else statement AnIf...Then statementcan be followed by an optionalElsestatement, which exe cutes when the boolean expression is false.

    nested If statements You can use one Ifor Else ifs tatement inside another Ifor Else ifstatement(s).

    Select Case statement A Select Casestatement allows a variable to be tested for equalityag ainst a list of values.

    nested Se lect Case statements You can use one select case s tatement inside another select casestatement(s).

    VB.NET - LOOPS

    There may be a situation when you need to exe cute a block of code several number of times. In g eneralstatements are executed sequentially: The first statement in a function is executed first, followed by the second,and so on.

    Prog ramming lang uages provide various control structures that allow for more complicated execution paths.

    http://localhost/var/www/apps/conversion/tmp/scratch_6/vb.net/vb.net_nested_select_case_statements.htmhttp://localhost/var/www/apps/conversion/tmp/scratch_6/vb.net/vb.net_select_case_statements.htmhttp://localhost/var/www/apps/conversion/tmp/scratch_6/vb.net/vb.net_nested_if_statements.htmhttp://localhost/var/www/apps/conversion/tmp/scratch_6/vb.net/vb.net_if_else_statements.htmhttp://localhost/var/www/apps/conversion/tmp/scratch_6/vb.net/vb.net_if_statements.htm
  • 5/28/2018 Vb.net Quick Guide

    28/114

    A loop statement allows us to execute a statement or g roup of statements multiple times and following is theg eneral form of a loop statement in most of the prog ramming lang uag es:

    VB.Net provides following types of loop to handle looping requirements. Click the following links to check theirdetail.

    Loop Type Description

    Do Loop It repeats the enclosed block of statements while a Boolean condition isTrue or until the condition becomes True. It could be terminated at any time

    with the Exit Do statement.

    For...Next It repeats a g roup of statements a spe cified number of times and a loopindex counts the number of loop iterations as the loop executes.

    For Each...Next It repeats a g roup of statements for each element in a collection. T his loopis used for acce ssing and manipulating all elements in an array or a VB.Netcollection.

    While... End While It executes a series of statements as long as a g iven condition is T rue.

    With... End With It is not exactly a looping construct. It exe cutes a series of statements thatrepe atedly refers to a sing le obje ct or structure.

    Nested loops You can use one or more loop inside any another While, For or Do loop.

    Loop Control Statements:

    Loop control statements chang e execution from its normal sequence . When exe cution leaves a scope, allautomatic obje cts that were cre ated in that scope are destroyed.

    VB.Net provides the following control statements. Click the following links to check their detail.

    Control Statement Description

    Exit statement Terminates the loo or select casestatement and transfers execution to

    http://localhost/var/www/apps/conversion/tmp/scratch_6/vb.net/vb.net_exit_statement.htmhttp://localhost/var/www/apps/conversion/tmp/scratch_6/vb.net/vb.net_nested_loops.htmhttp://localhost/var/www/apps/conversion/tmp/scratch_6/vb.net/vb.net_with_statement.htmhttp://localhost/var/www/apps/conversion/tmp/scratch_6/vb.net/vb.net_while_loops.htmhttp://localhost/var/www/apps/conversion/tmp/scratch_6/vb.net/vb.net_foreachnext_loops.htmhttp://localhost/var/www/apps/conversion/tmp/scratch_6/vb.net/vb.net_fornext_loops.htmhttp://localhost/var/www/apps/conversion/tmp/scratch_6/vb.net/vb.net_do_loops.htm
  • 5/28/2018 Vb.net Quick Guide

    29/114

    the statement immediately following the loop or s elect case.

    Continue statement Causes the loop to skip the remainder of its body and immediately retest itscondition prior to reiterating .

    GoTo statement Transfers control to the labe led statement. Though it is not advised to useGoTo statement in your prog ram.

    VB.NET - STRINGS

    In VB.Net, you can use string s as array of characters, however, more common practice is to use the Stringkeyword to declare a string variable. T he string keyword is an alias for the System.Stringclass .

    Creating a String Object

    You can cre ate 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 re trieving 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:

    Modulestrings SubMain() Dimfname,lname,fullname,greetings AsString 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 Dimsarray()AsString={"Hello","From","Tutorials","Point"} Dimmessage AsString=String.Join(" ",sarray) Console.WriteLine("Message: {0}",message)

    'formatting method to convert a valueDim 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 SubEnd Module

    When the above code is compiled and exe cuted, it produces the following result:

    Full Name: Rowan AtkinsonGreetings: Hello

    Message: Hello From Tutorials PointMessage: Message sent at 5:58 PM on Wednesday, December 12, 2012

    Properties of the String Class

    The String class has the following two properties:

    http://localhost/var/www/apps/conversion/tmp/scratch_6/vb.net/vb.net_goto_statement.htmhttp://localhost/var/www/apps/conversion/tmp/scratch_6/vb.net/vb.net_continue_statement.htm
  • 5/28/2018 Vb.net Quick Guide

    30/114

    S.N Property Name & Description

    1 CharsGets the Charobject at a specified position in the currentStringobject.

    2 LengthGets the number of characters in the current String obj ect.

    Methods of the String Class

    The String class has numerous methods that help you in working with the string obj ects. T he following tableprovides some of the most commonly use d methods:

    S.N Method Name & Description

    1 Public Shared Function Compare ( strA As String , strB As String ) As Integ erCompares two specified string obj ects and returns an integ er that indicates their re lative pos ition in

    the sort order.

    2 Public Shared Function Compare ( strA As String, strB As String, ignoreCase AsBoolean ) As IntegerCompares two specified string obj ects and returns an integ er that indicates their re lative pos ition inthe sort order. Howeve r, it ig nore s case if the Boolean parameter is true.

    3 Public Shared Function Concat ( str0 As String , str1 As String ) As StringConcatenates two string objects.

    4 Public Shared Function Concat ( str0 As String , str1 As String , str2 As String ) AsString

    Concatenates three string objects.

    5 Public Shared Function Concat ( str0 As String , str1 As String , str2 As String , str3As String ) As StringConcatenates four string objects.

    6 Public Function Contains ( value As String ) As BooleanReturns a value indicating whether the specified string obj ect occurs within this string .

    7 Public Shared Function Copy ( str As String ) As StringCreates a new String object with the same value as the specified string .

    8 pPublic Sub CopyTo ( sourceIndex As Integer, destination As Char(),

    destinationIndex As Integ er, count As Integ er )Copies a specified number of characters from a specified position of the string object to a specifiedposition in an array of Unicode characters.

    9 Public Function EndsWith ( value As String ) As BooleanDe termines whether the end of the string object matches the specified string .

    10 Public Function Equals ( value As String ) As BooleanDe termines whether the current string object and the spe cified string object have the same value.

    11 Public Shared Function Equals ( a As String , b As String ) As BooleanDe termines whether two specified string objects have the same value.

    12 Public Shared Function Format ( format As S tring , arg 0 As O bjec t ) As StringReplace s one or more format items in a specified string with the string representation of a specifiedobject.

    13 Public Function IndexOf ( value As Char ) As Inte er

  • 5/28/2018 Vb.net Quick Guide

    31/114

    Returns the ze ro-based index of the first occurrence of the specified Unicode character in the currentstring .

    14 Public Function IndexOf ( value As String ) As Integ erReturns the ze ro-based index of the first occurrence of the specified string in this instance .

    15 Public Function IndexOf ( value As Char, startIndex As Integer ) As IntegerReturns the ze ro-based index of the first occurrence of the specified Unicode character in this string ,starting search at the specified character pos ition.

    16 Public Function IndexOf ( value As String , startIndex As Integ er ) As Integ erReturns the zero-based index of the first occurre nce of the s pecified string in this instance , startingsearch at the specified character position.

    17 Public Function IndexOfAny ( anyOf As Char() ) As Integ erReturns the ze ro-based index of the first occurrence in this instance of any character in a specifiedarray of Unicode characters.

    18 Public Function IndexOfAny ( anyOf As Char(), startIndex As Integer ) As IntegerReturns the ze ro-based index of the first occurrence in this instance of any character in a specifiedarray of Unicode characters , starting search at the specified character position.

    19 Public Function Insert ( startIndex As Integer, value As String ) As StringReturns a new string in which a specified string is inserted at a specified index pos ition in the curre ntstring object.

    20 Public Shared Function IsNullOrEmpty ( value As String ) As BooleanIndicates whether the specified string is null or an Empty string .

    21 Public Shared Function Join ( separator As String, ParamArray value As String() )As StringConcatenates all the elements of a s tring array, using the specified separator between each element.

    22 Public Shared Function Join ( separator As String, value As String(), startIndex As

    Integer, count As Integer ) As StringConcatenates the s pecified elements of a string array, using the specified se parator betwee n eachelement.

    23 Public Function LastIndexOf ( value As Char ) As Integ erReturns the ze ro-based index pos ition of the last occurrence of the specified Unicode character withinthe current string object.

    24 Public Function LastIndexOf ( value As String ) As Integ erReturns the ze ro-based index pos ition of the last occurrence of a s pecified string within the currentstring object.

    25 Public Function Remove ( startIndex As Integ er ) As StringRemove s all the characters in the curre nt instance , beg inning at a specified position and continuingthrough the last position, and returns the string .

    26 Public Function Remove ( startIndex As Integ er, count As Integ er ) As StringRemove s the specified number of characters in the current string beg inning at a specified position andreturns the string .

    27 Public Function Replace ( oldChar As Char, newChar As Char ) As StringReplace s all occurrence s of a specified Unicode character in the current string object with thespecified Unicode character and re turns the new string .

    28 Public Function Replace ( oldValue As String, newValue As String ) As StringReplace s all occurrence s of a specified string in the current string object with the specified string andreturns the new string .

    29 Public Function Split ( ParamArray separator As Char() ) As String ()Returns a string array that contains the substring s in the current string obj ect, de limited by elements

  • 5/28/2018 Vb.net Quick Guide

    32/114

    of a specified Unicode character array.

    30 Public Function Split ( separator As Char(), c ount As Integ er ) As String ()Returns a string array that contains the substring s in the current string obj ect, de limited by elementsof a specified Unicode character array. The int parameter specifies the maximum number ofsubstring s to re turn.

    31 Public Function StartsWith ( value As String ) As BooleanDe termines whether the beg inning of this string instance matches the specified string .

    32 Public Function ToCharArray As Char()Returns a Unicode character array with all the characters in the curre nt string obj ect.

    33 Public Function To CharArray ( startIndex As Integ er, length As Integ er ) AsChar()Returns a Unicode character array with all the characters in the curre nt string obj ect, starting from thespecified index and up to the specified length.

    34 Public Function ToLower As StringReturns a copy of this s tring converted to lowercase.

    35 Public Function ToUpper As StringReturns a copy of this s tring converted to uppercase.

    36 Public Function Trim As StringRemoves all leading and trailing white-s pace characters from the current String object.

    VB.NET - DATE & TIME

    Most of the software you write needs implementing some form of date functions returning curre nt date and time.Dates are so much part of everyday life that it becomes easy to work with them without thinking . VB.Ne t alsoprovides powerful tools for date arithmetic that makes manipulating dates easy.

    The Date data type contains date values, time values, or date and time values. The default value of Date is0:00:00 (midnig ht) on January 1, 0001. T he equivalent .NET data type is System.DateTime.

    The DateTime structure represents an instant in time, typically expressed as a date and time of day

    'Declaration _Public Structure DateTime _Implements IComparable, IFormattable, IConvertible, ISerializable,IComparable(Of DateTime), IEquatable(Of DateTime)

    You can also g et the current date and time from the DateAndTime class.

    The DateAndTimemodule contains the procedures and properties used in date and time operations.

    'Declaration _Public NotInheritable Class DateAndTime

    Note:

    Both the DateTime structure and the DateAndTime module contains properties like Nowand Today, so

    often beg inners find it confusing . T he DateAndTime class belong s to the Microsoft.VisualBasic namespaceand the DateT ime structure belongs to the System namespace .Therefore, using the later would help you in porting your code to another .Ne t lang uag e like C #. Howeve r,the DateAndTime class/module contains all the leg acy date functions available in Visual Basic.

  • 5/28/2018 Vb.net Quick Guide

    33/114

    Properties and Methods of the DateTime Structure

    The following table lists some of the commonly used propertiesof the DateTime Structure:

    S.N Property Description

    1 Date Gets the date component of this instance .

    2 Day Gets the day of the month represented by this instance.

    3 DayOfWeek Gets the day of the wee k repre sented by this instance .

    4 DayOfYear Gets the day of the year represented by this instance .

    5 Hour Gets the hour component of the date represented by this instance.

    6 Kind Gets a value that indicates whether the time represented by this instance isbased on local time, Coordinated Universal Time (UT C), or neither.

    7 Millisecond Gets the milliseconds component of the date represented by this instance.

    8 Minute Gets the minute component of the date represented by this instance.

    9 Month Gets the month component of the date represented by this instance.

    10 Now Gets a DateTime object that is set to the curre nt date and time on thiscomputer, expressed as the local time.

    11 Second Gets the seconds component of the date re presented by this instance .

    12 Ticks Gets the number of ticks that represent the date and time of this instance .

    13 TimeOfDay Gets the time of day for this instance .

    14 Today Gets the current date.

    15 UtcNow Gets a DateTime object that is set to the curre nt date and time on thiscomputer, expresse d as the Coordinated Universal Time (UTC ).

    16 Year Gets the year component of the date re prese nted by this instance .

    The following table lists some of the commonly used methodsof the DateTime s tructure:

    S.N Method Name & Description

    1 Public Function Add ( value As TimeSpan ) As DateTimeReturns a new DateT ime that adds the value of the specified TimeSpan to the value of this instance .

    2 Public Function AddDays ( value As Double ) As DateTimeReturns a new DateT ime that adds the specified number of days to the value of this instance .

    3 Public Function AddHours ( value As Double ) As DateTimeReturns a new DateT ime that adds the specified number of hours to the value of this instance .

    4 Public Function AddMinutes ( value As Double ) As DateTime

    Returns a new DateTime that adds the specified number of minutes to the value of this instance .

    5 Public Function AddMonths ( months As Integer ) As DateTimeReturns a new DateTime that adds the specified number of months to the value of this instance .

    6 Public Function AddSeconds ( value As Double ) As DateTime

  • 5/28/2018 Vb.net Quick Guide

    34/114

    Returns a new DateTime that adds the specified number of seconds to the value of this instance.

    7 Public Function AddYears ( value As Integer ) As DateTimeReturns a new DateTime that adds the specified number of years to the value of this instance.

    8 Public Shared Function Compare ( t1 As DateT ime, t2 As DateT ime ) As Integ erCompares two instance s of DateT ime and re turns an integ er that indicates whether the first instance isearlier than, the same as, or later than the second instance.

    9 Public Function CompareT o ( value As DateT ime ) As Integ erCompares the value of this instance to a specified DateTime value and returns an integ er that indicateswhether this instance is e arlier than, the same as, or later than the specified DateTime value.

    10 Public Function Equals ( value As DateTime ) As BooleanReturns a value indicating whether the value of this instance is equal to the value of the specifiedDateT ime instance .

    11 Public Shared Function Equals ( t1 As DateTime, t2 As DateTime ) As BooleanReturns a value indicating whether two DateT ime instance s have the same date and time value.

    12 Public Overrides Function ToString As StringConverts the value of the current DateT ime object to its equivalent string representation.

    The above list of methods is not exhaustive, please visit Microsoft documentationfor the complete list of methodsand prope rties of the DateT ime structure.

    Creating a DateTime Object

    You can cre ate a DateTime object, in one of the following ways:

    By calling a DateTime constructor from any of the overloaded DateT ime constructors .

    By assigning the DateT ime object a date and time value returned by a property or method.

    By parsing the string representation of a date and time value.

    By calling the DateTime structure's implicit default constructor.

    The following example demonstrates this:

    ModuleModule1 SubMain() 'DateTime constructor: parameters year, month, day, hour, min, sec Dim date1 As New Date(2012, 12, 16, 12, 0, 0) 'initializes a newDateTimevalue Dimdate2 AsDate=#12/16/2012 12:00:52 AM#

    'using properties Dim date3 As Date = Date.Now Dim date4 As Date = Date.UtcNow Dim date5 As Date = Date.Today Console.WriteLine(date1) Console.WriteLine(date2) Console.WriteLine(date3) Console.WriteLine(date4) Console.WriteLine(date5) Console.ReadKey() End SubEnd Module

    When the above code was compiled and executed, it produced the following result:

    12/16/2012 12:00:00 PM12/16/2012 12:00:52 PM12/12/2012 10:22:50 PM12/12/2012 12:00:00 PM

    http://msdn.microsoft.com/en-us/library/system.datetime.aspx
  • 5/28/2018 Vb.net Quick Guide

    35/114

    Getting the Current Date and Time:

    The following prog rams demonstrate how to get the curre nt date and time in VB.Net:

    Current Time:

    ModuledateNtime SubMain() Console.Write("Current Time: ")

    Console.WriteLine(Now.ToLongTimeString) Console.ReadKey() EndSubEndModule

    When the above code is compiled and exe cuted, it produces the following result:

    Current Time: 11 :05 :32 AM

    Current Date:

    ModuledateNtime

    SubMain() Console.WriteLine("Current Date: ") Dimdt AsDate=Today Console.WriteLine("Today is: {0}",dt) Console.ReadKey() EndSubEndModule

    When the above code is compiled and exe cuted, it produces the following result:

    Today is: 12/11/2012 12:00:00 AM

    Formatting Date

    A Date literal should be enclosed within hash signs (# #), and specified in the format M/d/yyyy, for example#12/16/2012#. Otherwise, your code may chang e depending on the locale in which your application is running .

    For example, you specified Date literal of #2/6/2012# for the date February 6, 2012. It is alrig ht for the localethat uses mm/dd/yyyy format. Howeve r, in a locale that uses dd/mm/yyyy format, your literal would compile toJune 2, 2012. If a locale uses another format say, yyyy/mm/dd, the literal would be invalid and cause a compilererror.

    To convert a Date literal to the format of your locale, or to a custom format, use the Formatfunction of Stringclass, specifying either a predefined or user-de fined date format.

    The following example demonstrates this.

    ModuledateNtime SubMain() Console.WriteLine("India Wins Freedom: ") DimindependenceDay AsNewDate(1947,8,15,0,0,0) ' Use format specifiers to control the date display. Console.WriteLine(" Format 'd:' " & independenceDay.ToString("d")) Console.WriteLine(" Format 'D:' " & independenceDay.ToString("D")) Console.WriteLine(" Format 't:' " & independenceDay.ToString("t")) Console.WriteLine(" Format 'T:' " & independenceDay.ToString("T")) Console.WriteLine(" Format 'f:' " & independenceDay.ToString("f")) Console.WriteLine(" Format 'F:' " & independenceDay.ToString("F"))

    Console.WriteLine(" Format 'g:' " & independenceDay.ToString("g")) Console.WriteLine(" Format 'G:' " & independenceDay.ToString("G")) Console.WriteLine(" Format 'M:' " & independenceDay.ToString("M")) Console.WriteLine(" Format 'R:' " & independenceDay.ToString("R")) Console.WriteLine(" Format 'y:' " & independenceDay.ToString("y")) Console.ReadKey() End Sub

  • 5/28/2018 Vb.net Quick Guide

    36/114

    End Module

    When the above code is compiled and exe cuted, it produces the following result:

    India Wins Freedom:Format 'd:' 8/15/1947Format 'D:' Friday, August 15, 1947Format 't:' 12:00 AMFormat 'T:' 12:00:00 AMFormat 'f:' Friday, August 15, 1947 12:00 AMFormat 'F:' Friday, August 15, 1947 12:00:00 AMFormat 'g:' 8/15/1947 12:00 AMFormat 'G:' 8/15/1947 12:00:00 AMFormat 'M:' 8/15/1947 August 15Format 'R:' Fri, 15 August 1947 00:00:00 GMTFormat 'y:' August, 1947

    Predefined Date/Time Formats

    The following table identifies the predefined date and time format names. These may be used by name as thestyle arg ument for the Formatfunction:

    Format Description

    General Date, or G Displays a date and/or time. For example, 1/12/2012 07:07:30 AM.

    Long Date,MediumDate, o r D

    Displays a date according to your current culture's long date format. Forexample, Sunday, December 16, 2012.

    Short Date, o r d Displays a date using your current culture's short date format. For example,12/12/2012.

    Long Time,Medium

    Time, orT

    Displays a time using your curre nt culture 's long time format; typically includes

    hours, minutes, seconds. For example, 01:07:30 AM.

    Short Time or t Displays a time using your curre nt culture 's short time format. For e xample, 11:07AM.

    f Displays the long date and short time according to your curre nt culture's format.For example, Sunday, December 16, 2012 12:15 AM.

    F Displays the long date and long time according to your curre nt culture's format.For example, Sunday, December 16, 2012 12:15:31 AM.

    g Displays the short date and short time according to your curre nt culture 's format.For example, 12/16/2012 12:15 AM.

    M, m Displays the month and the day of a date. For example, Dece mber 16.

    R, r Formats the date according to the RFC1123Pattern prope rty.

    s Formats the date and time as a sortable index. For e xample, 2012-12-16T12:07:31.

    u Formats the date and time as a GMT sortable index. For example, 2012-12-1612:15:31Z.

    U Formats the date and time with the long date and long time as GMT. For example,

    Sunday, December 16, 2012 6:07:31 PM.

    Y, y Formats the date as the year and month. For example, De ce mber, 2012.

    For other formats like, user-de fined formats, please consult Microsoft Documentation.

    http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.strings.format.aspx
  • 5/28/2018 Vb.net Quick Guide

    37/114

    Properties and Methods of the DateAndTime Class

    The following table lists some of the commonly used propertiesof the DateAndTimeClass:

    S.N Property Description

    1 Date Returns or sets a String value represe nting the current date according to

    your system.

    2 Now Returns a Date value containing the curre nt date and time according toyour system.

    3 TimeOfDay Returns or sets a Date value containing the curre nt time of day accordingto your system.

    4 Timer Returns a Double value represe nting the number of se conds e lapsedsince midnight.

    5 TimeString Returns or se ts a String value represe nting the current time of dayaccording to your system.

    6 Today Gets the current date.

    The following table lists some of the commonly used methodsof the DateAndTimeclass:

    S.N Method Name & Description

    1 Public Shared Function DateAdd ( Interval As DateInterval, Number As Do uble,DateValue As DateTime ) As DateTime

    Returns a Date value containing a date and time value to which a specified time interval has beenadded.

    2 Public Shared Function DateAdd ( Interval As String, Number As Double,DateValue As Objec t ) As DateT imeReturns a Date value containing a date and time value to which a specified time interval has beenadded.

    3 Public Shared Function DateDiff ( Interval As DateInterval, Date1 As DateT ime,Date2 As DateTime, DayOfWeek As FirstDayOfWeek, WeekOfYear AsFirstWeekOfYear ) As LongReturns a Long value specifying the number of time intervals be tween two Date values.

    4 Public Shared Function DatePart ( Interval As DateInterval, DateValue AsDateTime, FirstDayOfWeekValue As FirstDayOfWeek, FirstWeekOfYearValue AsFirstWeekOfYear ) As IntegerReturns an Integ er value containing the specified component of a g iven Date value.

    5 Public Shared Function Day ( DateValue As DateT ime ) As Integ erReturns an Integ er value from 1 through 31 representing the day of the month.

    6 Public Shared Function Hour ( TimeValue As DateT ime ) As Integ erReturns an Integ er value from 0 throug h 23 re presenting the hour of the day.

    7 Public Shared Function Minute ( T imeValue As DateT ime ) As Integ erReturns an Integ er value from 0 throug h 59 representing the minute of the hour.

    8 Public Shared Function Month ( DateValue As DateTime ) As IntegerReturns an Integ er value from 1 through 12 re presenting the month of the year.

    9 Public Shared Function MonthName ( Month As Inte er, Ab breviate As Boolean )

  • 5/28/2018 Vb.net Quick Guide

    38/114

    As StringReturns a String value containing the name of the specified month.

    10 Public Shared Function Second ( T imeValue As DateT ime ) As Integ erReturns an Integ er value from 0 throug h 59 representing the second of the minute.

    11 Public Overridable Function ToString As StringReturns a string that repre sents the current obje ct.

    12 Public Shared Function Weekday ( DateValue As DateTime, DayOfWeek AsFirstDayOfWeek ) As IntegerReturns an Integ er value containing a number re presenting the day of the week.

    13 Public Shared Function WeekdayName ( Weekday As Integer, Abbreviate AsBoolean, FirstDayOfWeekValue As FirstDayOfWeek ) As StringReturns a String value containing the name of the specified weekday.

    14 Public Shared Function Year ( DateValue As DateTime ) As IntegerReturns an Integ er value from 1 through 9999 represe nting the year.

    The above list is not exhaustive. For complete list of properties and methods of the DateAndTime class, pleaseconsult Microsoft Documentation.

    The following prog ram demonstrates some of these and methods:

    ModuleModule1 SubMain() Dimbirthday AsDate Dimbday AsInteger Dimmonth AsInteger Dimmonthname AsString ' Assign a date using standard short format. birthday = #7/27/1998#

    bday = Microsoft.VisualBasic.DateAndTime.Day(birthday) month = Microsoft.VisualBasic.DateAndTime.Month(birthday) monthname = Microsoft.VisualBasic.DateAndTime.MonthName(month) Console.WriteLine(birthday) Console.WriteLine(bday) Console.WriteLine(month) Console.WriteLine(monthname) Console.ReadKey() End SubEnd Module

    When the above code is compiled and exe cuted, it produces the following result:

    7/27/1998 12:00:00 AM277July

    VB.NET - ARRAYS

    To de clare an array in VB.Net, you use the Dim statement. For example,

    DimintData(30) ' an array of 31 elementsDim strData(20) As String 'an array of 21stringsDimtwoDarray(10,20)AsInteger'a two dimensional array of integersDim ranges(10, 100) 'a two dimensional array

    You can also initialize the array e lements while de claring the array. For example,

    DimintData()AsInteger={12,16,20,24,28,32}Dimnames()AsString={"Karthik","Sandhya",_"Shivangi","Ashwitha","Somnath"}

    http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.dateandtime.aspx
  • 5/28/2018 Vb.net Quick Guide

    39/114

    DimmiscData()AsObject={"Hello World",12d,16ui,"A"c}

    The elements in an array can be store d and accessed by using the index of the array. T he following prog ramdemonstrates this:

    ModulearrayApl SubMain() Dimn(10)AsInteger ' n is an array of 10 integers ' Dimi,j AsInteger ' initialize elements of array n '

    Fori =0To10 n(i)=i +100' set element at location i to i + 100

    Next i 'output each array element's value ' Forj =0To10 Console.WriteLine("Element({0}) = {1}",j,n(j)) Nextj Console.ReadKey() EndSubEndModule

    When the above code is compiled and exe cuted, it produces the following result:

    Element(0) = 100Element(1) = 101Element(2) = 102Element(3) = 103Element(4) = 104Element(5) = 105Element(6) = 106Element(7) = 107Element(8) = 108Element(9) = 109Element(10) = 110

    Dynamic ArraysDynamic arrays are arrays that can be dimensioned and re-dimensioned as par the need of the prog ram. Youcan declare a dynamic array using the ReDims tatement.

    Syntax for ReDim statement:

    ReDim[Preserve]arrayname(subscripts)

    Where,

    The Preservekeyword helps to preserve the data in an existing array, when you resize it.

    arraynameis the name of the array to re-dimension.

    subscriptsspecifies the new dimension.

    ModulearrayApl SubMain() Dimmarks()AsInteger ReDimmarks(2) marks(0)=85 marks(1)=75 marks(2)=90 ReDimPreservemarks(10) marks(3)=80 marks(4)=76 marks(5)=92 marks(6)=99 marks(7)=79 marks(8)=75 Fori =0To10 Console.WriteLine(i &vbTab &marks(i))

  • 5/28/2018 Vb.net Quick Guide

    40/114

    Nexti

    Console.ReadKey() EndSubEndModule

    When the above code is compiled and exe cuted, it produces the following result:

    0 851 752 903 804 765 926 997 798 759 010 0

    Multi-Dimensional Arrays

    VB.Net allows multidimensional arrays. Multi-dimensional arrays are also called rectang ular array.

    You can declare a 2-dimensional array of string s as:

    DimtwoDStringArray(10,20)AsString

    or, a three dimensional array of Integ er variables:

    DimthreeDIntArray(10,10,10)AsInteger

    The following prog ram demonstrates creating and using a 2-dimensional array:

    ModulearrayApl SubMain() ' 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 ' Fori =0To4 Forj =0To1 Console.WriteLine("a[{0},{1}] = {2}",i,j,a(i,j)) Nextj Nexti Console.ReadKey() EndSubEndModule

    When the above code is compiled and exe cuted, it produces the following result:

    a[0,0]: 0a[0,1]: 0a[1,0]: 1a[1,1]: 2a[2,0]: 2a[2,1]: 4a[3,0]: 3a[3,1]: 6a[4,0]: 4a[4,1]: 8

    Jagg ed Array

    A Jagg ed array is an array of arrays. The follwoing code shows declaring a jag g ed array named scoresofIntegers:

  • 5/28/2018 Vb.net Quick Guide

    41/114

    Dimscores AsInteger()()=NewInteger(5)(){}

    The following example illustrates using a jag g ed array:

    ModulearrayApl SubMain() '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 SubEnd Module

    When the above code is compiled and exe cuted, it produces the following result:

    a[0][0]: 0a[0][1]: 0a[1][0]: 1a[1][1]: 2a[2][0]: 2a[2][1]: 4a[3][0]: 3a[3][1]: 6a[4][0]: 4a[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 . T he Arrayclass provides various properties and methods to work with arrays.

    Properties of the Array Class

    The following table provides some of the most commonly use d properties of theArrayclass :

    S.N Property Name & Description

    1 IsFixedSizeGets a value indicating whether the Array has a fixed s ize.

    2 IsReadOnlyGets a value indicating whether the Array is read-only.

    3 LengthGets a 32-bit integ er that represents the total number of elements in all the dimensions of the Array.

    4 LongLengthGets a 64-bit integ er that represents the total number of elements in all the dimensions of the Array.

    5 RankGets the rank (number of dimensions) of the Array.

    Methods of the Array Class

  • 5/28/2018 Vb.net Quick Guide

    42/114

    The following table provides some of the most commonly use d methodsof theArrayclass:

    S.N Method Name & Description

    1 Public Shared Sub Clear ( array As Array, index As Integ er, length As Integ er )Sets a rang e of elements in the Array to zero, to false, or to null, de pending on the element type.

    2 Public Shared Sub Copy ( sourceArray As Array, destinationArray As Array,length As Integer )Copies a range of elements from an Array s tarting at the first element and pastes them into another

    Array starting at the first element. The length is specified as a 32-bit integ er.

    3 Public Sub CopyTo ( array As Array, index As Integer )Copies all the elements of the current one-dimensional Array to the specified one-dimensional Arraystarting at the specified destination Array index. T he index is specified as a 32-bit integ er.

    4 Public Function GetLength ( dimension As Integ er ) As Integ erGets a 32-bit integ er that represents the number of elements in the specified dimension of the Array.

    5 Public Function GetLongLeng th ( dimension As Integ er ) As LongGets a 64-bit integ er that represents the number of elements in the specified dimension of the Array.

    6 Public Function GetLowerBound ( dimension As Integ er ) As Integ erGets the lower bound of the specified dimension in the Array.

    7 Public Function GetType As TypeGets the Type of the current instance . (Inherited from Object.)

    8 Public Function GetUpperBound ( dimension As Integ er ) As Integ erGets the upper bound of the specified dimension in the Array.

    9 Public Function GetValue ( index As Integ er ) As Objec t

    Gets the value at the specified position in the one-dimensional Array. The index is specified as a 32-bitinteg er.

    10 Public Shared Function IndexOf ( array As Array, value As O bjec t ) As Integ erSearches for the specified object and returns the index of the first occurrence within the entire one-dimensional Array.

    11 Public Shared Sub Reverse ( array As Array )Reverses the sequence of the elements in the entire one-dimensional Array.

    12 Public Sub Se tValue ( value As O bject, index As Integ er )Sets a value to the element at the specified pos ition in the one-dimensional Array. The index is

    specified as a 32-bit integer.

    13 Public Shared Sub Sort ( array As Array )Sorts the e lements in an entire one-dimensional Array using the IComparable implementation of eachelement of the Array.

    14 Public Overridable Function To String As Stringeturns a string that repre sents the current obje ct. (Inherited from Obje ct.)

    For complete list of Array class properties and methods, please consult Microsoft documentation.

    Example

    The following prog ram demonstrates use of some of the methods of the Array class :

    ModulearrayApl SubMain()

  • 5/28/2018 Vb.net Quick Guide

    43/114

    Dimlist AsInteger()={34,72,13,44,25,30,10} Dimtemp AsInteger()=list Dimi AsInteger Console.Write("Original Array: ") ForEachi Inlist Console.Write("{0} ",i) Nexti 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: ") ForEachi Inlist Console.Write("{0} ",i) Nexti Console.WriteLine() Console.ReadKey() EndSub

    EndModule

    When the above code is compiled and exe cuted, it produces the following result:

    Original Array: 34 72 13 44 25 30 10Reversed Array: 10 30 25 44 13 72 34Sorted Array: 10 13 25 30 34 44 72

    VB.NET - COLLECTIONS

    Collection classe s are specialize d class es for data storage and retrieval. These classe s provide support forstacks, queues, lists, and hash tables. Mos t collection class es implement the same interfaces.

    Collection classes se rve various purpose s, such as allocating memory dynamically to elements and accessing alist of items on the basis of an index etc. These classes create collections of objects of the Object class, which isthe base class for all data types in C#.

    Various Collection Classes and Their Usag e

    The following are the various commonly use d class es of the System.Collectionnamespace. Click thefollowing links to check their details.

    Class Description and Useag e

    ArrayListIt represents orde red collection of an object that can be indexedindividually.

    It is basically an alternative to an array. However, unlike array, you can add and removeitems from a list at a specified position using an inde