Vb.net Tutorial

download Vb.net Tutorial

of 123

description

Vb.net Tutorial

Transcript of Vb.net Tutorial

http://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htmCopyrighttutorialspoint.comVB.NET-QUICKGUIDEVB.NET-OVERVIEWVisualBasic.NET(VB.NET)isanobject-orientedcomputerprogramminglanguageimplementedonthe.NETFramework.AlthoughitisanevolutionofclassicVisualBasiclanguage,itisnotbackwards-compatiblewithVB6,andanycodewrittenintheoldversiondoesnotcompileunderVB.NET.Likeallother.NETlanguages,VB.NEThascompletesupportforobject-orientedconcepts.EverythinginVB.NETisanobject,includingalloftheprimitivetypes(Short,Integer,Long,String,Boolean,etc.)anduserdefinedtypes,events,andevenassemblies.AllobjectsinheritsfromthebaseclassObject.VB.NETisimplementedofMicrosoft's.NETframework.Thereforeithasfullaccessallthelibrariesinthe.NetFramework.It'salsopossibletorunVB.NETprogramsonMono,theopen-sourcealternativeto.NET,notonlyunderWindows,butevenLinuxorMacOSX.ThefollowingreasonsmakeVB.Netawidelyusedprofessionallanguage:Modern,generalpurpose.Objectoriented.Componentoriented.Easytolearn.Structuredlanguage.Itproducesefficientprograms.Itcanbecompiledonavarietyofcomputerplatforms.Partof.NetFramework.StrongProgrammingFeaturesVB.NetVB.Nethasnumerousstrongprogrammingfeaturesthatmakeitendearingtomultitudeofprogrammersworldwide.Letusmentionsomeofthesefeatures:BooleanConditionsAutomaticGarbageCollectionStandardLibraryAssemblyVersioningPropertiesandEventsDelegatesandEventsManagementEasytouseGenericsIndexersConditionalCompilation

SimpleMultithreadingVB.NET-ENVIRONMENTIntegratedDevelopmentEnvironment(IDE)ForVB.NetMicrosoftprovidesthefollowingdevelopmenttoolsforVB.Netprogramming:VisualStudio2010(VS)VisualBasic2010Express(VBE)VisualWebDeveloperThelasttwoarefree.UsingthesetoolsyoucanwriteallkindsofVB.Netprogramsfromsimplecommand-lineapplicationstomorecomplexapplications.VisualBasicExpressandVisualWebDeveloperExpresseditionaretrimmeddownversionsofVisualStudioandhasthesamelookandfeel.TheyretainmostfeaturesofVisualStudio.Inthistutorial,wehaveusedVisualBasic2010ExpressandVisualWebDeveloper(forthewebprogrammingchapter).Youcandownloaditfromhere.Itgetsautomaticallyinstalledinyourmachine.Pleasenotethatyouneedanactiveinternetconnectionforinstallingtheexpressedition.WritingVB.NetProgramsonLinuxorMacOSAlthoughthe.NETFrameworkrunsontheWindowsoperatingsystem,therearesomealternativeversionsthatworkonotheroperatingsystems.Monoisanopen-sourceversionofthe.NETFramework,whichincludesaVisualBasiccompilerandrunsonseveraloperatingsystems,includingvariousflavorsofLinuxandMacOS.ThemostrecentversionisVB2012.ThestatedpurposeofMonoisnotonlytobeabletorunMicrosoft.NETapplicationscross-platform,butalsotobringbetterdevelopmenttoolstoLinuxdevelopers.MonocanberunonmanyoperatingsystemsincludingAndroid,BSD,iOS,Linux,OSX,Windows,SolarisandUNIX.VB.NET-PROGRAMSTRUCTUREBeforewestudybasicbuildingblocksoftheVB.Netprogramminglanguage,letuslookabareminimumVB.Netprogramstructuresothatwecantakeitasareferenceinupcomingchapters.VB.NetHelloWorldExampleAVB.Netprogrambasicallyconsistsofthefollowingparts:NamespacedeclarationAclassormoduleOneormoreproceduresVariablesTheMainprocedureStatements&ExpressionsComments

Letuslookatasimplecodethatwouldprintthewords"HelloWorld":ImportsSystemModuleModule1'ThisprogramwilldisplayHelloWorldSubMain()Console.WriteLine("HelloWorld")Console.ReadKey()EndSubEndModuleWhentheabovecodeiscompiledandexecuted,itproducesfollowingresult:Hello,World!Letuslookvariouspartsoftheaboveprogram:ThefirstlineoftheprogramImportsSystemisusedtoincludetheSystemnamespaceintheprogram.ThenextlinehasaModuledeclaration,themoduleModule1.VB.Netiscompletelyobjectoriented,soeveryprogrammustcontainamoduleofaclassthatcontainsthedataandproceduresthatyourprogramuses.ClassesorModulesgenerallywouldcontainmorethanoneprocedure.Procedurescontaintheexecutablecode,orinotherwords,theydefinethebehavioroftheclass.Aprocedurecouldbeanyofthefollowing:FunctionSubOperatorGetSetAddHandlerRemoveHandlerRaiseEventThenextline('Thisprogram)willbeignoredbythecompilerandithasbeenputtoaddadditionalcommentsintheprogram.ThenextlinedefinestheMainprocedure,whichistheentrypointforallVB.Netprograms.TheMainprocedurestateswhatthemoduleorclasswilldowhenexecuted.TheMainprocedurespecifiesitsbehaviorwiththestatementConsole.WriteLine("HelloWorld")WriteLineisamethodoftheConsoleclassdefinedintheSystemnamespace.Thisstatementcausesthemessage"Hello,World!"tobedisplayedonthescreen.ThelastlineConsole.ReadKey()isfortheVS.NETUsers.ThiswillpreventthescreenfromrunningandclosingquicklywhentheprogramislaunchedfromVisualStudio.NET.Compile&ExecuteVB.NetProgram:IfyouareusingVisualStudio.NetIDE,takethefollowingsteps:

StartVisualStudio.Onthemenubar,chooseFile,New,Project.ChooseVisualBasicfromtemplatesChooseConsoleApplication.SpecifyanameandlocationforyourprojectusingtheBrowsebutton,andthenchoosetheOKbutton.ThenewprojectappearsinSolutionExplorer.WritecodeintheCodeEditor.ClicktheRunbuttonortheF5keytoruntheproject.ACommandPromptwindowappearsthatcontainsthelineHelloWorld.VB.NET-BASICSYNTAXVB.Netisanobjectorientedprogramminglanguage.InObjectOrientedProgrammingmethodologyaprogramconsistsofvariousobjectsthatinteractwitheachotherbymeansofactions.Theactionsthatanobjectmaytakearecalledmethods.Objectsofthesamekindaresaidtohavethesametypeor,moreoften,aresaidtobeinthesameclass.WhenweconsideraVB.Netprogramitcanbedefinedasacollectionofobjectsthatcommunicateviainvokingeachother'smethods.Letusnowbrieflylookintowhatdoclass,object,methodsandinstantvariablesmean.Object-Objectshavestatesandbehaviors.Example:Adoghasstates-color,name,breedaswellasbehaviors-wagging,barking,eatingetc.Anobjectisaninstanceofaclass.Class-Aclasscanbedefinedasatemplate/blueprintthatdescribethebehaviors/statesthatobjectofitstypesupport.Methods-Amethodisbasicallyabehavior.Aclasscancontainmanymethods.Itisinmethodswherethelogicsarewritten,dataismanipulatedandalltheactionsareexecuted.InstantVariables-Eachobjecthasitsuniquesetofinstantvariables.Anobject'sstateiscreatedbythevaluesassignedtotheseinstantvariables.ARectangleClassinVB.NetForexample,letusconsideraRectangleobject.Ithasattributeslikelengthandwidth.Dependinguponthedesign,itmayneedwaysforacceptingthevaluesoftheseattributes,calculatingareaanddisplaydetails.LetuslookatanimplementationofaRectangleclassanddiscussVB.Netbasicsyntax,onthebasisofourobservationsinit:ImportsSystemPublicClassRectanglePrivatelengthAsDoublePrivatewidthAsDouble'PublicmethodsPublicSubAcceptDetails()length=4.5width=3.5EndSubPublicFunctionGetArea()AsDoubleGetArea=length*width

EndFunctionPublicSubDisplay()Console.WriteLine("Length:{0}",length)Console.WriteLine("Width:{0}",width)Console.WriteLine("Area:{0}",GetArea())EndSubSharedSubMain()DimrAsNewRectangle()r.Acceptdetails()r.Display()Console.ReadLine()EndSubEndClassWhentheabovecodeiscompiledandexecuted,itproducesfollowingresult:Length:4.5Width:3.5Area:15.75Inpreviouschapter,wecreatedaVisualBasicmodulethatheldthecode.SubMainindicatestheentrypointofVB.Netprogram.Here,weareusingClassthatcontainsbothcodeanddata.Youuseclassestocreateobjects.Forexample,inthecode,risaRectangleobject.Anobjectisaninstanceofaclass:DimrAsNewRectangle()Aclassmayhavemembersthatcanbeaccessiblefromoutsideclass,ifsospecified.Datamembersarecalledfieldsandproceduremembersarecalledmethods.Sharedmethodsorstaticmethodscanbeinvokedwithoutcreatinganobjectoftheclass.Instancemethodsareinvokedthroughanobjectoftheclass:SharedSubMain()DimrAsNewRectangle()r.Acceptdetails()r.Display()Console.ReadLine()EndSubIdentifiersAnidentifierisanameusedtoidentifyaclass,variable,function,oranyotheruser-defineditem.ThebasicrulesfornamingclassesinVB.Netareasfollows:Anamemustbeginwithaletterthatcouldbefollowedbyasequenceofletters,digits(0-9)orunderscore.Thefirstcharacterinanidentifiercannotbeadigit.Itmustnotcontainanyembeddedspaceorsymbollike?-+!@#%^&*()[]{}.;:"'/and\.Howeveranunderscore(_)canbeused.Itshouldnotbeareservedkeyword.VB.NetKeywordsThefollowingtableliststheVB.Netreservedkeywords:

AddHandlerAddressOfAliasAndAndAlsoAsBooleanByRefByteByValCallCaseCatchCBoolCByteCCharCDateCDecCDblCharCIntClassCLngCObjConstContinueCSByteCShortCSngCStrCTypeCUIntCULngCUShortDateDecimalDeclareDefaultDelegateDimDirectCastDoDoubleEachElseElseIfEndEndIfEnumEraseErrorEventExitFalseFinallyForFriendFunctionGetGetTypeGetXMLNamespaceGlobalGoToHandlesIfImplementsImportsInInheritsIntegerInterfaceIsIsNotLetLibLikeLongLoopMeModModuleMustInheritMustOverrideMyBaseMyClassNamespaceNarrowingNewNextNotNothingNotInheritableNotOverridableObjectOfOnOperatorOptionOptionalOrOrElseOverloadsOverridableOverridesParamArrayPartialPrivatePropertyProtectedPublicRaiseEventReadOnlyReDimREMRemoveHandlerResumeReturnSByteSelectSetShadowsSharedShortSingleStaticStepStopStringStructureSubSyncLockThenThrowToTrueTryTryCastTypeOfUIntegerWhileWideningWithWithEventsWriteOnlyXorVB.NET-DATATYPESDatatypesrefertoanextensivesystemusedfordeclaringvariablesorfunctionsofdifferenttypes.Thetypeofavariabledetermineshowmuchspaceitoccupiesinstorageandhowthebitpatternstoredisinterpreted.DataTypesAvailableinVB.NetVB.Netprovidesawiderangeofdatatypes.Thefollowingtableshowsallthedatatypesavailable:DataTypeStorageAllocationValueRange

BooleanDependsonimplementingplatformTrueorFalseByte1byte0through255(unsigned)Char2bytes0through65535(unsigned)Date8bytes0:00:00(midnight)onJanuary1,0001through11:59:59PMonDecember31,9999Decimal16bytes0through+/-79,228,162,514,264,337,593,543,950,335(+/-7.9...E+28)withnodecimalpoint;0through+/-7.9228162514264337593543950335with28placestotherightofthedecimalDouble8bytes-1.79769313486231570E+308through-4.94065645841246544E-324,fornegativevalues4.94065645841246544E-324through1.79769313486231570E+308,forpositivevaluesInteger4bytes-2,147,483,648through2,147,483,647(signed)Long8bytes-9,223,372,036,854,775,808through9,223,372,036,854,775,807(signed)Object4byteson32-bitplatform8byteson64-bitplatformAnytypecanbestoredinavariableoftypeObjectSByte1byte-128through127(signed)Short2bytes-32,768through32,767(signed)Single4bytes-3.4028235E+38through-1.401298E-45fornegativevalues;1.401298E-45through3.4028235E+38forpositivevaluesStringDependsonimplementingplatform0toapproximately2billionUnicodecharactersUInteger4bytes0through4,294,967,295(unsigned)ULong8bytes0through18,446,744,073,709,551,615(unsigned)User-DefinedDependsonimplementingplatformEachmemberofthestructurehasarangedeterminedbyitsdatatypeandindependentoftherangesoftheothermembersUShort2bytes0through65,535(unsigned)

ExampleThefollowingexampledemonstratesuseofsomeofthetypes:ModuleDataTypesSubMain()DimbAsByteDimnAsIntegerDimsiAsSingleDimdAsDoubleDimdaAsDateDimcAsCharDimsAsStringDimblAsBooleanb=1n=1234567si=0.12345678901234566d=0.12345678901234566da=Todayc="U"cs="Me"IfScriptEngine="VB"Thenbl=TrueElsebl=FalseEndIfIfblThen'theoathtakingConsole.Write(c&"and,"&s&vbCrLf)Console.WriteLine("declaringonthedayof:{0}",da)Console.WriteLine("WewilllearnVB.Netseriously")Console.WriteLine("Letsseewhathappenstothefloatingpointvariables:")Console.WriteLine("TheSingle:{0},TheDouble:{1}",si,d)EndIfConsole.ReadKey()EndSubEndModuleWhentheabovecodeiscompiledandexecuted,itproducesfollowingresult:Uand,Medeclaringonthedayof:12/4/201212:00:00PMWewilllearnVB.NetseriouslyLetsseewhathappenstothefloatingpointvariables:TheSingle:0.1234568,TheDouble:0.123456789012346TheTypeConversionFunctionsinVB.NetVB.Netprovidesthefollowinginlinetypeconversionfunctions:S.NFunctionss&Description1CBool(expression)ConvertstheexpressiontoBooleandatatype.2CByte(expression)ConvertstheexpressiontoBytedatatype.3CChar(expression)ConvertstheexpressiontoChardatatype.4CDate(expression)

ConvertstheexpressiontoDatedatatype5CDbl(expression)ConvertstheexpressiontoDoubledatatype.6CDec(expression)ConvertstheexpressiontoDecimaldatatype.7CInt(expression)ConvertstheexpressiontoIntegerdatatype.8CLng(expression)ConvertstheexpressiontoLongdatatype.9CObj(expression)ConvertstheexpressiontoObjecttype.10CSByte(expression)ConvertstheexpressiontoSBytedatatype.11CShort(expression)ConvertstheexpressiontoShortdatatype.12CSng(expression)ConvertstheexpressiontoSingledatatype.13CStr(expression)ConvertstheexpressiontoStringdatatype.14CUInt(expression)ConvertstheexpressiontoUIntdatatype.15CULng(expression)ConvertstheexpressiontoULngdatatype.16CUShort(expression)ConvertstheexpressiontoUShortdatatype.Example:Thefollowingexampledemonstratessomeofthesefunctions:ModuleDataTypesSubMain()DimnAsIntegerDimdaAsDateDimblAsBoolean=Truen=1234567da=TodayConsole.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

Whentheabovecodeiscompiledandexecuted,itproducesfollowingresult:True-1True12/4/201211VB.NET-VARIABLESAvariableisnothingbutanamegiventoastorageareathatourprogramscanmanipulate.EachvariableinVB.Nethasaspecifictype,whichdeterminesthesizeandlayoutofthevariable'smemory;therangeofvaluesthatcanbestoredwithinthatmemory;andthesetofoperationsthatcanbeappliedtothevariable.Wehavealreadydiscussedvariousdatatypes.ThebasicvaluetypesprovidedinVB.Netcanbecategorizedas:TypeExampleIntegraltypesSByte,Byte,Short,UShort,Integer,UInteger,Long,ULongandCharFloatingpointtypesSingleandDoubleDecimaltypesDecimalBooleantypesTrueorFalsevalues,asassignedDatetypesDateVB.NetalsoallowsdefiningothervaluetypesofvariablelikeEnumandreferencetypesofvariableslikeClass.WewilldiscussdatetypesandClasses,insubsequentchapters.VariableDeclarationinVB.NetTheDimstatementisusedforvariabledeclarationandstorageallocationforoneormorevariables.TheDimstatementisusedatmodule,class,structure,procedureorblocklevel.SyntaxforvariabledeclarationinVB.Netis:[][accessmodifier][[Shared][Shadows]|[Static]][ReadOnly]Dim[WithEvents]variablelistWhere,attributelistisalistofattributesthatapplytothevariable.Optional.accessmodifierdefinestheaccesslevelsofthevariables,ithasvaluesas-Public,Protected,Friend,ProtectedFriendandPrivate.Optional.Shareddeclaresasharedvariable,whichisnotassociatedwithanyspecificinstanceofaclassorstructure,ratheravailabletoalltheinstancesoftheclassorstructure.Optional.Shadowsindicatethatthevariablere-declaresandhidesanidenticallynamedelement,orsetofoverloadedelements,inabaseclass.Optional.

Staticindicatesthatthevariablewillretainitsvalue,evenwhentheafterterminationoftheprocedureinwhichitisdeclared.Optional.ReadOnlymeansthevariablecanberead,butnotwritten.Optional.WithEventsspecifiesthatthevariableisusedtorespondtoeventsraisedbytheinstanceassignedtothevariable.Optional.Variablelistprovidesthelistofvariablesdeclared.Eachvariableinthevariablelisthasthefollowingsyntaxandparts:variablename[([boundslist])][As[New]datatype][=initializer]Where,variablename:isthenameofthevariableboundslist:optional.Itprovideslistofboundsofeachdimensionofanarrayvariable.New:optional.ItcreatesanewinstanceoftheclasswhentheDimstatementruns.datatype:RequiredifOptionStrictisOn.Itspecifiesthedatatypeofthevariable.initializer:OptionalifNewisnotspecified.Expressionthatisevaluatedandassignedtothevariablewhenitiscreated.Somevalidvariabledeclarationsalongwiththeirdefinitionareshownhere:DimStudentIDAsIntegerDimStudentNameAsStringDimSalaryAsDoubleDimcount1,count2AsIntegerDimstatusAsBooleanDimexitButtonAsNewSystem.Windows.Forms.ButtonDimlastTime,nextTimeAsDateVariableInitializationinVB.NetVariablesareinitialized(assignedavalue)withanequalsignfollowedbyaconstantexpression.Thegeneralformofinitializationis:variable_name=value;forexample,DimpiAsDoublepi=3.14159Youcaninitializeavariableatthetimeofdeclarationasfollows:DimStudentIDAsInteger=100DimStudentNameAsString="BillSmith"ExampleTryfollowingexamplewhichmakesuseofvarioustypesofvariables:

ModulevariablesNdataypesSubMain()DimaAsShortDimbAsIntegerDimcAsDoublea=10b=20c=a+bConsole.WriteLine("a={0},b={1},c={2}",a,b,c)Console.ReadLine()EndSubEndModuleWhentheabovecodeiscompiledandexecuted,itproducesfollowingresult:a=10,b=20,c=30AcceptingValuesfromUserTheConsoleclassintheSystemnamespaceprovidesafunctionReadLineforacceptinginputfromtheuserandstoreitintoavariable.Forexample,DimmessageAsStringmessage=Console.ReadLineThefollowingexampledemonstratesit:ModulevariablesNdataypesSubMain()DimmessageAsStringConsole.Write("Entermessage:")message=Console.ReadLineConsole.WriteLine()Console.WriteLine("YourMessage:{0}",message)Console.ReadLine()EndSubEndModuleWhentheabovecodeiscompiledandexecuted,itproducesfollowingresult(AssumetheuserinputsHelloWorld):Entermessage:HelloWorldYourMessage:HelloWorldVB.NET-CONSTANTSANDENUMERATIONSTheconstantsrefertofixedvaluesthattheprogrammaynotalterduringitsexecution.Thesefixedvaluesarealsocalledliterals.Constantscanbeofanyofthebasicdatatypeslikeanintegerconstant,afloatingconstant,acharacterconstant,orastringliteral.Therearealsoenumerationconstantsaswell.Theconstantsaretreatedjustlikeregularvariablesexceptthattheirvaluescannotbemodifiedaftertheirdefinition.Anenumerationisasetofnamedintegerconstants.DeclaringConstantsInVB.Net,constantsaredeclaredusingtheConststatement.TheConststatementisusedatmodule,class,structure,procedure,orblocklevelforuseinplaceofliteralvalues.

ThesyntaxfortheConststatementis:[][accessmodifier][Shadows]ConstconstantlistWhere,attributelist:specifiesthelistofattributesappliedtotheconstants;youcanprovidemultipleattributes,separatedbycommas.Optional.accessmodifier:specifieswhichcodecanaccesstheseconstants.Optional.Valuescanbeeitherofthe:Public,Protected,Friend,ProtectedFriend,orPrivate.Shadows:thismakestheconstanthideaprogrammingelementofidenticalname,inabaseclass.Optional.Constantlist:givesthelistofnamesofconstantsdeclared.Required.Where,eachconstantnamehasthefollowingsyntaxandparts:constantname[Asdatatype]=initializerconstantname:specifiesthenameoftheconstantdatatype:specifiesthedatatypeoftheconstantinitializer:specifiesthevalueassignedtotheconstantForexample,'Thefollowingstatementsdeclareconstants.ConstmaxvalAsLong=4999PublicConstmessageAsString="HELLO"PrivateConstpiValueAsDouble=3.1415ExampleThefollowingexampledemonstratesdeclarationanduseofaconstantvalue:ModuleconstantsNenumSubMain()ConstPI=3.14149Dimradius,areaAsSingleradius=7area=PI*radius*radiusConsole.WriteLine("Area="&Str(area))Console.ReadKey()EndSubEndModuleWhentheabovecodeiscompiledandexecuted,itproducesfollowingresult:Area=153.933PrintandDisplayConstantsinVB.NetVB.Netprovidesthefollowingprintanddisplayconstants:ConstantDescription

vbCrLfCarriagereturn/linefeedcharactercombination.vbCrCarriagereturncharacter.vbLfLinefeedcharacter.vbNewLineNewlinecharacter.vbNullCharNullcharacter.vbNullStringNotthesameasazero-lengthstring("");usedforcallingexternalprocedures.vbObjectErrorErrornumber.User-definederrornumbersshouldbegreaterthanthisvalue.Forexample:Err.Raise(Number)=vbObjectError+1000vbTabTabcharacter.vbBackBackspacecharacter.DeclaringEnumerationsAnenumeratedtypeisdeclaredusingtheEnumstatement.TheEnumstatementdeclaresanenumerationanddefinesthevaluesofitsmembers.TheEnumstatementcanbeusedatthemodule,class,structure,procedure,orblocklevel.ThesyntaxfortheEnumstatementisasfollows:[][accessmodifier][Shadows]Enumenumerationname[Asdatatype]memberlistEndEnumWhere,attributelist:referstothelistofattributesappliedtothevariable.Optional.asscessmodifier:specifieswhichcodecanaccesstheseenumerations.Optional.Valuescanbeeitherofthe:Public,Protected,FriendorPrivate.Shadows:thismakestheenumerationhideaprogrammingelementofidenticalname,inabaseclass.Optional.enumerationname:nameoftheenumeration.Requireddatatype:specifiesthedatatypeoftheenumerationandallitsmembers.memberlist:specifiesthelistofmemberconstantsbeingdeclaredinthisstatement.Required.Eachmemberinthememberlisthasthefollowingsyntaxandparts:[]membername[=initializer]Where,name:specifiesthenameofthemember.Required.initializer:valueassignedtotheenumerationmember.Optional.

Forexample,EnumColorsred=1orange=2yellow=3green=4azure=5blue=6violet=7EndEnumExampleThefollowingexampledemonstratesdeclarationanduseoftheEnumvariableColors:ModuleconstantsNenumEnumColorsred=1orange=2yellow=3green=4azure=5blue=6violet=7EndEnumSubMain()Console.WriteLine("TheColorRedis:"&Colors.red)Console.WriteLine("TheColorYellowis:"&Colors.yellow)Console.WriteLine("TheColorBlueis:"&Colors.blue)Console.WriteLine("TheColorGreenis:"&Colors.green)Console.ReadKey()EndSubEndModuleWhentheabovecodeiscompiledandexecuted,itproducesfollowingresult:TheColorRedis:1TheColorYellowis:3TheColorBlueis:6TheColorGreenis:4VB.NET-MODIFIERSThemodifiersarekeywordsaddedwithanyprogrammingelement,togivesomeespecialemphasisonhowtheprogrammingelementwillbehave,orwillbeaccessedintheprogramForexample,theaccessmodifiers:Public,Private,Protected,Friend,ProtectedFriendetc.,indicatestheaccesslevelofaprogrammingelementlikeavariable,constant,enumerationoraclass.ListofAvailableModifiersinVB.NetThefollowingtableprovidesthecompletelistofVB.Netmodifiers:S.NModifierDescription1AnsiSpecifiesthatVisualBasicshouldmarshalallstringstoAmericanNationalStandardsInstitute(ANSI)valuesregardlessofthenameoftheexternalprocedurebeingdeclared.2AssemblySpecifiesthatanattributeatthebeginningofasourcefileappliestotheentire

assembly.3AsyncIndicatesthatthemethodorlambdaexpressionthatitmodifiesisasynchronous.Suchmethodsarereferredtoasasyncmethods.Thecallerofanasyncmethodcanresumeitsworkwithoutwaitingfortheasyncmethodtofinish..4AutoThecharsetmodifierpartintheDeclarestatementsuppliesthecharactersetinformationformarshalingstringsduringacalltotheexternalprocedure.ItalsoaffectshowVisualBasicsearchestheexternalfilefortheexternalprocedurename.TheAutomodifierspecifiesthatVisualBasicshouldmarshalstringsaccordingto.NETFrameworkrules.5ByRefSpecifiesthatanargumentispassedbyreference,i.e.,thecalledprocedurecanchangethevalueofavariableunderlyingtheargumentinthecallingcode.Itisusedunderthecontextsof:DeclareStatementFunctionStatementSubStatement6ByValSpecifiesthatanargumentispassedinsuchawaythatthecalledprocedureorpropertycannotchangethevalueofavariableunderlyingtheargumentinthecallingcode.Itisusedunderthecontextsof:DeclareStatementunctionStatementOperatorStatementPropertyStatementSubStatement7DefaultIdentifiesapropertyasthedefaultpropertyofitsclass,structure,orinterface.8FriendSpecifiesthatoneormoredeclaredprogrammingelementsareaccessiblefromwithintheassemblythatcontainstheirdeclaration,notonlybythecomponentthatdeclaresthem.Friendaccessisoftenthepreferredlevelforanapplication'sprogrammingelements,andFriendisthedefaultaccesslevelofaninterface,amodule,aclass,orastructure.9InItisusedingenericinterfacesanddelegates.10IteratorSpecifiesthatafunctionorGetaccessorisaniterator.Aniteratorperformsacustomiterationoveracollection.11KeyTheKeykeywordenablesyoutospecifybehaviorforpropertiesofanonymoustypes.12ModuleSpecifiesthatanattributeatthebeginningofasourcefileappliestothecurrentassemblymodule.ItisnotsameastheModulestatement.13MustInheritSpecifiesthataclasscanbeusedonlyasabaseclassandthatyoucannotcreate

anobjectdirectlyfromit.14MustOverrideSpecifiesthatapropertyorprocedureisnotimplementedinthisclassandmustbeoverriddeninaderivedclassbeforeitcanbeused.15NarrowingIndicatesthataconversionoperator(CType)convertsaclassorstructuretoatypethatmightnotbeabletoholdsomeofthepossiblevaluesoftheoriginalclassorstructure.16NotInheritableSpecifiesthataclasscannotbeusedasabaseclass.17NotOverridableSpecifiesthatapropertyorprocedurecannotbeoverriddeninaderivedclass.18OptionalSpecifiesthataprocedureargumentcanbeomittedwhentheprocedureiscalled.19OutForgenerictypeparameters,theOutkeywordspecifiesthatthetypeiscovariant.20OverloadsSpecifiesthatapropertyorprocedureredeclaresoneormoreexistingpropertiesorprocedureswiththesamename.21OverridableSpecifiesthatapropertyorprocedurecanbeoverriddenbyanidenticallynamedpropertyorprocedureinaderivedclass.22OverridesSpecifiesthatapropertyorprocedureoverridesanidenticallynamedpropertyorprocedureinheritedfromabaseclass.23ParamArrayParamArrayallowsyoutopassanarbitrarynumberofargumentstotheprocedure.AParamArrayparameterisalwaysdeclaredusingByVal.24PartialIndicatesthataclassorstructuredeclarationisapartialdefinitionoftheclassorstructure.25PrivateSpecifiesthatoneormoredeclaredprogrammingelementsareaccessibleonlyfromwithintheirdeclarationcontext,includingfromwithinanycontainedtypes.26ProtectedSpecifiesthatoneormoredeclaredprogrammingelementsareaccessibleonlyfromwithintheirownclassorfromaderivedclass.27PublicSpecifiesthatoneormoredeclaredprogrammingelementshavenoaccessrestrictions.28ReadOnlySpecifiesthatavariableorpropertycanbereadbutnotwritten.29ShadowsSpecifiesthatadeclaredprogrammingelementredeclaresandhidesanidenticallynamedelement,orsetofoverloadedelements,inabaseclass.30SharedSpecifiesthatoneormoredeclaredprogrammingelementsareassociatedwithaclassorstructureatlarge,andnotwithaspecificinstanceoftheclassorstructure.31StaticSpecifiesthatoneormoredeclaredlocalvariablesaretocontinuetoexistandretaintheirlatestvaluesafterterminationoftheprocedureinwhichtheyaredeclared.

32UnicodeSpecifiesthatVisualBasicshouldmarshalallstringstoUnicodevaluesregardlessofthenameoftheexternalprocedurebeingdeclared.33WideningIndicatesthataconversionoperator(CType)convertsaclassorstructuretoatypethatcanholdallpossiblevaluesoftheoriginalclassorstructure.34WithEventsSpecifiesthatoneormoredeclaredmembervariablesrefertoaninstanceofaclassthatcanraiseevents.35WriteOnlySpecifiesthatapropertycanbewrittenbutnotread.VB.NET-STATEMENTSAstatementisacompleteinstructioninVisualBasicprograms.Itmaycontainkeywords,operators,variables,literalvalues,constantsandexpressions.Statementscouldbecategorizedas:Declarationstatements-thesearethestatementswhereyounameavariable,constant,orprocedure,andcanalsospecifyadatatype.Executablestatements-thesearethestatements,whichinitiateactions.Thesestatementscancallamethodorfunction,looporbranchthroughblocksofcodeorassignvaluesorexpressiontoavariableorconstant.Inthelastcase,itiscalledanAssignmentstatement.DeclarationStatementsThedeclarationstatementsareusedtonameanddefineprocedures,variables,properties,arrays,andconstants.Whenyoudeclareaprogrammingelement,youcanalsodefineitsdatatype,accesslevel,andscope.Theprogrammingelementsyoumaydeclareincludevariables,constants,enumerations,classes,structures,modules,interfaces,procedures,procedureparameters,functionreturns,externalprocedurereferences,operators,properties,events,anddelegates.FollowingarethedeclarationstatementsinVB.Net:S.NStatementsandDescriptionExample1DimStatementDeclaresandallocatesstoragespaceforoneormorevariables.DimnumberAsIntegerDimquantityAsInteger=100DimmessageAsString="Hello!"2ConstStatementDeclaresanddefinesoneormoreconstants.ConstmaximumAsLong=1000ConstnaturalLogBaseAsObject=CDec(2.7182818284)3EnumStatementDeclaresanenumerationanddefinesthevaluesofitsmembers.EnumCoffeeMugSizeJumboExtraLargeLargeMedium

SmallEndEnum4ClassStatementDeclaresthenameofaclassandintroducesthedefinitionofthevariables,properties,events,andproceduresthattheclasscomprises.ClassBoxPubliclengthAsDoublePublicbreadthAsDoublePublicheightAsDoubleEndClass5StructureStatementDeclaresthenameofastructureandintroducesthedefinitionofthevariables,properties,events,andproceduresthatthestructurecomprises.StructureBoxPubliclengthAsDoublePublicbreadthAsDoublePublicheightAsDoubleEndStructure6ModuleStatementDeclaresthenameofamoduleandintroducesthedefinitionofthevariables,properties,events,andproceduresthatthemodulecomprises.PublicModulemyModuleSubMain()DimuserAsString=InputBox("Whatisyourname?")MsgBox("Usernameis"&user)EndSubEndModule7InterfaceStatementDeclaresthenameofaninterfaceandintroducesthedefinitionsofthemembersthattheinterfacecomprises.PublicInterfaceMyInterfaceSubdoSomething()EndInterface8FunctionStatementDeclaresthename,parameters,andcodethatdefineaFunctionprocedure.FunctionmyFunction(ByValnAsInteger)AsDoubleReturn5.87*nEndFunction9SubStatementDeclaresthename,parameters,andcodethatdefineaSubprocedure.SubmySub(ByValsAsString)ReturnEndSub10DeclareStatementDeclaresareferencetoaprocedureimplementedinanexternalfile.DeclareFunctiongetUserNameLib"advapi32.dll"Alias"GetUserNameA"(ByVallpBufferAsString,ByRefnSizeAsInteger)AsInteger11OperatorStatementDeclarestheoperatorsymbol,operands,andcodethatdefineanoperatorprocedureonaclassorstructure.PublicSharedOperator+(ByValxAsobj,ByValyAsobj)AsobjDimrAsNewobj

DimrAsNewobj'implementioncodeforr=x+yReturnrEndOperator12PropertyStatementDeclaresthenameofaproperty,andthepropertyproceduresusedtostoreandretrievethevalueoftheproperty.ReadOnlyPropertyquote()AsStringGetReturnquoteStringEndGetEndProperty13EventStatementDeclaresauser-definedevent.PublicEventFinished()14DelegateStatementUsedtodeclareadelegate.DelegateFunctionMathOperator(ByValxAsDouble,ByValyAsDouble)AsDoubleExecutableStatementsAnexecutablestatementperformsanaction.Statementscallingaprocedure,branchingtoanotherplaceinthecode,loopingthroughseveralstatements,orevaluatinganexpressionareexecutablestatements.Anassignmentstatementisaspecialcaseofanexecutablestatement.ExampleThefollowingexampledemonstratesadecisionmakingstatement:ModuledecisionsSubMain()'localvariabledefinition'DimaAsInteger=10'checkthebooleanconditionusingifstatement'If(aChecksifthevalueofleftoperandisgreaterthanthevalueofrightoperand,ifyesthenconditionbecomestrue.(A>B)isnottrue.=B)isnottrue.

and>2willgive15whichis0000

rightbythenumberofbitsspecifiedbytherightoperand.1111AssignmentOperatorsTherearefollowingassignmentoperatorssupportedbyVB.Net:ShowExamplesOperatorDescriptionExample=Simpleassignmentoperator,AssignsvaluesfromrightsideoperandstoleftsideoperandC=A+BwillassignvalueofA+BintoC+=AddANDassignmentoperator,ItaddsrightoperandtotheleftoperandandassigntheresulttoleftoperandC+=AisequivalenttoC=C+A-=SubtractANDassignmentoperator,ItsubtractsrightoperandfromtheleftoperandandassigntheresulttoleftoperandC-=AisequivalenttoC=C-A*=MultiplyANDassignmentoperator,ItmultipliesrightoperandwiththeleftoperandandassigntheresulttoleftoperandC*=AisequivalenttoC=C*A/=DivideANDassignmentoperator,Itdividesleftoperandwiththerightoperandandassigntheresulttoleftoperand(floatingpointdivision)C/=AisequivalenttoC=C/A\=DivideANDassignmentoperator,Itdividesleftoperandwiththerightoperandandassigntheresulttoleftoperand(Integerdivision)C\=AisequivalenttoC=C\A^=Exponentiationandassignmentoperator.Itraisestheleftoperandtothepoweroftherightoperandandassignstheresulttoleftoperand.C^=AisequivalenttoC=C^A>2&=ConcatenatesaStringexpressiontoaStringvariableorpropertyandassignstheresulttothevariableorproperty.Str1&=Str2issameasStr1=Str1&Str2MiscellaneousOperatorsTherearefewotherimportantoperatorssupportedbyVB.Net.ShowExamplesOperatorDescriptionExampleAddressOfReturnstheaddressofaprocedure.AddHandlerButton1.Click,AddressOfButton1_Click

AwaitItisappliedtoanoperandinanasynchronousmethodorlambdaexpressiontosuspendexecutionofthemethoduntiltheawaitedtaskcompletes.DimresultAsres=AwaitAsyncMethodThatReturnsResult()AwaitAsyncMethod()GetTypeItreturnsaTypeobjectforthespecifiedtype.TheTypeobjectprovidesinformationaboutthetypesuchasitsproperties,methods,andevents.MsgBox(GetType(Integer).ToString())FunctionExpressionItdeclarestheparametersandcodethatdefineafunctionlambdaexpression.Dimadd5=Function(numAsInteger)num+5'prints10Console.WriteLine(add5(5))IfItusesshort-circuitevaluationtoconditionallyreturnoneoftwovalues.TheIfoperatorcanbecalledwiththreeargumentsorwithtwoarguments.Dimnum=5Console.WriteLine(If(num>=0,"Positive","Negative"))OperatorsPrecedenceinVB.NetOperatorprecedencedeterminesthegroupingoftermsinanexpression.Thisaffectshowanexpressionisevaluated.Certainoperatorshavehigherprecedencethanothers;forexample,themultiplicationoperatorhashigherprecedencethantheadditionoperator:Forexamplex=7+3*2;Herexisassigned13,not20becauseoperator*hashigherprecedencethan+soitfirstgetmultipliedwith3*2andthenaddsinto7.Hereoperatorswiththehighestprecedenceappearatthetopofthetable,thosewiththelowestappearatthebottom.Withinanexpression,higherprecedenceoperatorswillbeevaluatedfirst.ShowExamplesOperatorPrecedenceAwaitHighestExponentiation(^)Unaryidentityandnegation(+,-)Multiplicationandfloating-pointdivision(*,/)Integerdivision(\)Modulusarithmetic(Mod)Additionandsubtraction(+,-)Arithmeticbitshift()Allcomparisonoperators(=,,=,Is,IsNot,Like,

TypeOf...Is)Negation(Not)Conjunction(And,AndAlso)Inclusivedisjunction(Or,OrElse)Exclusivedisjunction(Xor)LowestVB.NET-DECISIONMAKINGDecisionmakingstructuresrequirethattheprogrammerspecifyoneormoreconditionstobeevaluatedortestedbytheprogram,alongwithastatementorstatementstobeexecutediftheconditionisdeterminedtobetrue,andoptionally,otherstatementstobeexecutediftheconditionisdeterminedtobefalse.Followingisthegeneralfromofatypicaldecisionmakingstructurefoundinmostoftheprogramminglanguages:VB.Netprovidesfollowingtypesofdecisionmakingstatements.Clickthefollowinglinkstochecktheirdetail.StatementDescriptionIf...ThenstatementAnIf...Thenstatementconsistsofabooleanexpressionfollowedbyoneormorestatements.If...Then...ElsestatementAnIf...ThenstatementcanbefollowedbyanoptionalElsestatement,whichexecuteswhenthebooleanexpressionisfalse.nestedIfstatementsYoucanuseoneIforElseifstatementinsideanotherIforElseifstatement(s).SelectCasestatementASelectCasestatementallowsavariabletobetestedforequalityagainstalistofvalues.

nestedSelectCasestatementsYoucanuseoneselectcasestatementinsideanotherselectcasestatement(s).VB.NET-LOOPSTheremaybeasituationwhenyouneedtoexecuteablockofcodeseveralnumberoftimes.Ingeneralstatementsareexecutedsequentially:Thefirststatementinafunctionisexecutedfirst,followedbythesecond,andsoon.Programminglanguagesprovidevariouscontrolstructuresthatallowformorecomplicatedexecutionpaths.Aloopstatementallowsustoexecuteastatementorgroupofstatementsmultipletimesandfollowingisthegeneralfromofaloopstatementinmostoftheprogramminglanguages:VB.Netprovidesfollowingtypesoflooptohandleloopingrequirements.Clickthefollowinglinkstochecktheirdetail.LoopTypeDescriptionDoLoopItrepeatstheenclosedblockofstatementswhileaBooleanconditionisTrueoruntiltheconditionbecomesTrue.ItcouldbeterminatedatanytimewiththeExitDostatement.For...NextItrepeatsagroupofstatementsaspecifiednumberoftimesandaloopindexcountsthenumberofloopiterationsastheloopexecutes.ForEach...NextItrepeatsagroupofstatementsforeachelementinacollection.ThisloopisusedforaccessingandmanipulatingallelementsinanarrayoraVB.Netcollection.While...EndWhileItexecutesaseriesofstatementsaslongasagivenconditionisTrue.With...EndWithItisnotexactlyaloopingconstruct.Itexecutesaseriesofstatementsthatrepeatedlyreferstoasingleobjectorstructure.

NestedloopsYoucanuseoneormoreloopinsideanyanotherWhile,FororDoloop.LoopControlStatements:Loopcontrolstatementschangeexecutionfromitsnormalsequence.Whenexecutionleavesascope,allautomaticobjectsthatwerecreatedinthatscopearedestroyed.VB.Netprovidesthefollowingcontrolstatements.Clickthefollowinglinkstochecktheirdetail.ControlStatementDescriptionExitstatementTerminatesthelooporselectcasestatementandtransfersexecutiontothestatementimmediatelyfollowingthelooporselectcase.ContinuestatementCausesthelooptoskiptheremainderofitsbodyandimmediatelyretestitsconditionpriortoreiterating.GoTostatementTransferscontroltothelabeledstatement.ThoughitisnotadvisedtouseGoTostatementinyourprogram.VB.NET-STRINGSInVB.Netyoucanusestringsasarrayofcharacters,however,morecommonpracticeistousetheStringkeywordtodeclareastringvariable.ThestringkeywordisanaliasfortheSystem.Stringclass.CreatingaStringObjectYoucancreatestringobjectusingoneofthefollowingmethods:ByassigningastringliteraltoaStringvariableByusingaStringclassconstructorByusingthestringconcatenationoperator(+)ByretrievingapropertyorcallingamethodthatreturnsastringBycallingaformattingmethodtoconvertavalueorobjecttoitsstringrepresentationThefollowingexampledemonstratesthis:ModulestringsSubMain()Dimfname,lname,fullname,greetingsAsStringfname="Rowan"lname="Atkinson"fullname=fname+""+lnameConsole.WriteLine("FullName:{0}",fullname)'byusingstringconstructorDimlettersAsChar()={"H","e","l","l","o"}greetings=NewString(letters)Console.WriteLine("Greetings:{0}",greetings)'methodsreturningStringDimsarray()AsString={"Hello","From","Tutorials","Point"}

DimmessageAsString=String.Join("",sarray)Console.WriteLine("Message:{0}",message)'formattingmethodtoconvertavalueDimwaitingAsDateTime=NewDateTime(2012,12,12,17,58,1)DimchatAsString=String.Format("Messagesentat{0:t}on{0:D}",waiting)Console.WriteLine("Message:{0}",chat)Console.ReadLine()EndSubEndModuleWhentheabovecodeiscompiledandexecuted,itproducesfollowingresult:FullName:RowanAtkinsonGreetings:HelloMessage:HelloFromTutorialsPointMessage:Messagesentat5:58PMonWednesday,December12,2012PropertiesoftheStringClassTheStringclasshasthefollowingtwoproperties:S.NPropertyName&Description1CharsGetstheCharobjectataspecifiedpositioninthecurrentStringobject.2LengthGetsthenumberofcharactersinthecurrentStringobject.MethodsoftheStringClassTheStringclasshasnumerousmethodsthathelpyouinworkingwiththestringobjects.Thefollowingtableprovidessomeofthemostcommonlyusedmethods:S.NMethodName&Description1PublicSharedFunctionCompare(strAAsString,strBAsString)AsIntegerComparestwospecifiedstringobjectsandreturnsanintegerthatindicatestheirrelativepositioninthesortorder.2PublicSharedFunctionCompare(strAAsString,strBAsString,ignoreCaseAsBoolean)AsIntegerComparestwospecifiedstringobjectsandreturnsanintegerthatindicatestheirrelativepositioninthesortorder.However,itignorescaseiftheBooleanparameteristrue.3PublicSharedFunctionConcat(str0AsString,str1AsString)AsStringConcatenatestwostringobjects.4PublicSharedFunctionConcat(str0AsString,str1AsString,str2AsString)AsStringConcatenatesthreestringobjects.5PublicSharedFunctionConcat(str0AsString,str1AsString,str2AsString,str3AsString)AsStringConcatenatesfourstringobjects.

6PublicFunctionContains(valueAsString)AsBooleanReturnsavalueindicatingwhetherthespecifiedstringobjectoccurswithinthisstring.7PublicSharedFunctionCopy(strAsString)AsStringCreatesanewStringobjectwiththesamevalueasthespecifiedstring.8pPublicSubCopyTo(sourceIndexAsInteger,destinationAsChar(),destinationIndexAsInteger,countAsInteger)CopiesaspecifiednumberofcharactersfromaspecifiedpositionofthestringobjecttoaspecifiedpositioninanarrayofUnicodecharacters.9PublicFunctionEndsWith(valueAsString)AsBooleanDetermineswhethertheendofthestringobjectmatchesthespecifiedstring.10PublicFunctionEquals(valueAsString)AsBooleanDetermineswhetherthecurrentstringobjectandthespecifiedstringobjecthavethesamevalue.11PublicSharedFunctionEquals(aAsString,bAsString)AsBooleanDetermineswhethertwospecifiedstringobjectshavethesamevalue.12PublicSharedFunctionFormat(formatAsString,arg0AsObject)AsStringReplacesoneormoreformatitemsinaspecifiedstringwiththestringrepresentationofaspecifiedobject.13PublicFunctionIndexOf(valueAsChar)AsIntegerReturnsthezero-basedindexofthefirstoccurrenceofthespecifiedUnicodecharacterinthecurrentstring.14PublicFunctionIndexOf(valueAsString)AsIntegerReturnsthezero-basedindexofthefirstoccurrenceofthespecifiedstringinthisinstance.15PublicFunctionIndexOf(valueAsChar,startIndexAsInteger)AsIntegerReturnsthezero-basedindexofthefirstoccurrenceofthespecifiedUnicodecharacterinthisstring,startingsearchatthespecifiedcharacterposition.16PublicFunctionIndexOf(valueAsString,startIndexAsInteger)AsIntegerReturnsthezero-basedindexofthefirstoccurrenceofthespecifiedstringinthisinstance,startingsearchatthespecifiedcharacterposition.17PublicFunctionIndexOfAny(anyOfAsChar())AsIntegerReturnsthezero-basedindexofthefirstoccurrenceinthisinstanceofanycharacterinaspecifiedarrayofUnicodecharacters.18PublicFunctionIndexOfAny(anyOfAsChar(),startIndexAsInteger)AsIntegerReturnsthezero-basedindexofthefirstoccurrenceinthisinstanceofanycharacterinaspecifiedarrayofUnicodecharacters,startingsearchatthespecifiedcharacterposition.19PublicFunctionInsert(startIndexAsInteger,valueAsString)AsStringReturnsanewstringinwhichaspecifiedstringisinsertedataspecifiedindexpositioninthecurrentstringobject.20PublicSharedFunctionIsNullOrEmpty(valueAsString)AsBooleanIndicateswhetherthespecifiedstringisnulloranEmptystring.21PublicSharedFunctionJoin(separatorAsString,ParamArrayvalueAsString())AsStringConcatenatesalltheelementsofastringarray,usingthespecifiedseparatorbetweeneachelement.

22PublicSharedFunctionJoin(separatorAsString,valueAsString(),startIndexAsInteger,countAsInteger)AsStringConcatenatesthespecifiedelementsofastringarray,usingthespecifiedseparatorbetweeneachelement.23PublicFunctionLastIndexOf(valueAsChar)AsIntegerReturnsthezero-basedindexpositionofthelastoccurrenceofthespecifiedUnicodecharacterwithinthecurrentstringobject.24PublicFunctionLastIndexOf(valueAsString)AsIntegerReturnsthezero-basedindexpositionofthelastoccurrenceofaspecifiedstringwithinthecurrentstringobject.25PublicFunctionRemove(startIndexAsInteger)AsStringRemovesallthecharactersinthecurrentinstance,beginningataspecifiedpositionandcontinuingthroughthelastposition,andreturnsthestring.26PublicFunctionRemove(startIndexAsInteger,countAsInteger)AsStringRemovesthespecifiednumberofcharactersinthecurrentstringbeginningataspecifiedpositionandreturnsthestring.27PublicFunctionReplace(oldCharAsChar,newCharAsChar)AsStringReplacesalloccurrencesofaspecifiedUnicodecharacterinthecurrentstringobjectwiththespecifiedUnicodecharacterandreturnsthenewstring.28PublicFunctionReplace(oldValueAsString,newValueAsString)AsStringReplacesalloccurrencesofaspecifiedstringinthecurrentstringobjectwiththespecifiedstringandreturnsthenewstring.29PublicFunctionSplit(ParamArrayseparatorAsChar())AsString()Returnsastringarraythatcontainsthesubstringsinthecurrentstringobject,delimitedbyelementsofaspecifiedUnicodecharacterarray.30PublicFunctionSplit(separatorAsChar(),countAsInteger)AsString()Returnsastringarraythatcontainsthesubstringsinthecurrentstringobject,delimitedbyelementsofaspecifiedUnicodecharacterarray.Theintparameterspecifiesthemaximumnumberofsubstringstoreturn.31PublicFunctionStartsWith(valueAsString)AsBooleanDetermineswhetherthebeginningofthisstringinstancematchesthespecifiedstring.32PublicFunctionToCharArrayAsChar()ReturnsaUnicodecharacterarraywithallthecharactersinthecurrentstringobject.33PublicFunctionToCharArray(startIndexAsInteger,lengthAsInteger)AsChar()ReturnsaUnicodecharacterarraywithallthecharactersinthecurrentstringobject,startingfromthespecifiedindexanduptothespecifiedlength.34PublicFunctionToLowerAsStringReturnsacopyofthisstringconvertedtolowercase.35PublicFunctionToUpperAsStringReturnsacopyofthisstringconvertedtouppercase.36PublicFunctionTrimAsStringRemovesallleadingandtrailingwhite-spacecharactersfromthecurrentStringobject.

VB.NET-DATE&TIMEMostofthesoftwareyouwriteneedsimplementingsomeformofdatefunctionsreturningcurrentdateandtime.Datesaresomuchpartofeverydaylifethatitbecomeseasytoworkwiththemwithoutthinking.VB.Netalsoprovidespowerfultoolsfordatearithmeticthatmakesmanipulatingdateseasy.TheDatedatatypecontainsdatevalues,timevalues,ordateandtimevalues.ThedefaultvalueofDateis0:00:00(midnight)onJanuary1,0001.Theequivalent.NETdatatypeisSystem.DateTime.TheDateTimestructurerepresentsaninstantintime,typicallyexpressedasadateandtimeofday'Declaration

_PublicStructureDateTime_ImplementsIComparable,IFormattable,IConvertible,ISerializable,IComparable(OfDateTime),IEquatable(OfDateTime)YoucanalsogetthecurrentdateandtimefromtheDateAndTimeclass.TheDateAndTimemodulecontainstheproceduresandpropertiesusedindateandtimeoperations.'Declaration

_PublicNotInheritableClassDateAndTimeNote:BoththeDateTimestructureandtheDateAndTimemodulecontainspropertieslikeNowandToday,sooftenbeginnersfinditconfusing.TheDateAndTimeclassbelongstotheMicrosoft.VisualBasicnamespaceandtheDateTimestructurebelongstotheSystemnamespace.Therefore,usingthelaterwouldhelpyouinportingyourcodetoanother.NetlanguagelikeC#.However,theDateAndTimeclass/modulecontainsallthelegacydatefunctionsavailableinVisualBasic.PropertiesandMethodsoftheDateTimeStructureThefollowingtablelistssomeofthecommonlyusedpropertiesoftheDateTimeStructure:S.NPropertyDescription1DateGetsthedatecomponentofthisinstance.2DayGetsthedayofthemonthrepresentedbythisinstance.3DayOfWeekGetsthedayoftheweekrepresentedbythisinstance.4DayOfYearGetsthedayoftheyearrepresentedbythisinstance.5HourGetsthehourcomponentofthedaterepresentedbythisinstance.6KindGetsavaluethatindicateswhetherthetimerepresentedbythisinstanceisbasedonlocaltime,CoordinatedUniversalTime(UTC),orneither.

7MillisecondGetsthemillisecondscomponentofthedaterepresentedbythisinstance.8MinuteGetstheminutecomponentofthedaterepresentedbythisinstance.9MonthGetsthemonthcomponentofthedaterepresentedbythisinstance.10NowGetsaDateTimeobjectthatissettothecurrentdateandtimeonthiscomputer,expressedasthelocaltime.11SecondGetsthesecondscomponentofthedaterepresentedbythisinstance.12TicksGetsthenumberofticksthatrepresentthedateandtimeofthisinstance.13TimeOfDayGetsthetimeofdayforthisinstance.14TodayGetsthecurrentdate.15UtcNowGetsaDateTimeobjectthatissettothecurrentdateandtimeonthiscomputer,expressedastheCoordinatedUniversalTime(UTC).16YearGetstheyearcomponentofthedaterepresentedbythisinstance.ThefollowingtablelistssomeofthecommonlyusedmethodsoftheDateTimestructure:S.NMethodName&Description1PublicFunctionAdd(valueAsTimeSpan)AsDateTimeReturnsanewDateTimethataddsthevalueofthespecifiedTimeSpantothevalueofthisinstance.2PublicFunctionAddDays(valueAsDouble)AsDateTimeReturnsanewDateTimethataddsthespecifiednumberofdaystothevalueofthisinstance.3PublicFunctionAddHours(valueAsDouble)AsDateTimeReturnsanewDateTimethataddsthespecifiednumberofhourstothevalueofthisinstance.4PublicFunctionAddMinutes(valueAsDouble)AsDateTimeReturnsanewDateTimethataddsthespecifiednumberofminutestothevalueofthisinstance.5PublicFunctionAddMonths(monthsAsInteger)AsDateTimeReturnsanewDateTimethataddsthespecifiednumberofmonthstothevalueofthisinstance.6PublicFunctionAddSeconds(valueAsDouble)AsDateTimeReturnsanewDateTimethataddsthespecifiednumberofsecondstothevalueofthisinstance.7PublicFunctionAddYears(valueAsInteger)AsDateTimeReturnsanewDateTimethataddsthespecifiednumberofyearstothevalueofthisinstance.8PublicSharedFunctionCompare(t1AsDateTime,t2AsDateTime)AsIntegerComparestwoinstancesofDateTimeandreturnsanintegerthatindicateswhetherthefirstinstanceisearlierthan,thesameas,orlaterthanthesecondinstance.9PublicFunctionCompareTo(valueAsDateTime)AsIntegerComparesthevalueofthisinstancetoaspecifiedDateTimevalueandreturnsanintegerthatindicates

whetherthisinstanceisearlierthan,thesameas,orlaterthanthespecifiedDateTimevalue.10PublicFunctionEquals(valueAsDateTime)AsBooleanReturnsavalueindicatingwhetherthevalueofthisinstanceisequaltothevalueofthespecifiedDateTimeinstance.11PublicSharedFunctionEquals(t1AsDateTime,t2AsDateTime)AsBooleanReturnsavalueindicatingwhethertwoDateTimeinstanceshavethesamedateandtimevalue.12PublicOverridesFunctionToStringAsStringConvertsthevalueofthecurrentDateTimeobjecttoitsequivalentstringrepresentation.Theabovelistofmethodsisnotexhaustive,pleasevisitMicrosoftdocumentationforthecompletelistofmethodsandpropertiesoftheDateTimestructure.CreatingaDateTimeObjectYoucancreateaDateTimeobject,inoneofthefollowingways:BycallingaDateTimeconstructorfromanyoftheoverloadedDateTimeconstructors.ByassigningtheDateTimeobjectadateandtimevaluereturnedbyapropertyormethod.Byparsingthestringrepresentationofadateandtimevalue.BycallingtheDateTimestructure'simplicitdefaultconstructor.Thefollowingexampledemonstratesthis:ModuleModule1SubMain()'DateTimeconstructor:parametersyear,month,day,hour,min,secDimdate1AsNewDate(2012,12,16,12,0,0)'initializesanewDateTimevalueDimdate2AsDate=#12/16/201212:00:52AM#'usingpropertiesDimdate3AsDate=Date.NowDimdate4AsDate=Date.UtcNowDimdate5AsDate=Date.TodayConsole.WriteLine(date1)Console.WriteLine(date2)Console.WriteLine(date3)Console.WriteLine(date4)Console.WriteLine(date5)Console.ReadKey()EndSubEndModuleWhentheabovecodewascompiledandexecuted,itproducedfollowingresult:12/16/201212:00:00PM12/16/201212:00:52PM12/12/201210:22:50PM12/12/201212:00:00PMGettingtheCurrentDateandTime:ThefollowingprogramsdemonstratehowtogetthecurrentdateandtimeinVB.Net:CurrentTime:

ModuledateNtimeSubMain()Console.Write("CurrentTime:")Console.WriteLine(Now.ToLongTimeString)Console.ReadKey()EndSubEndModuleWhentheabovecodeiscompiledandexecuted,itproducesfollowingresult:CurrentTime:11:05:32AMCurrentDate:ModuledateNtimeSubMain()Console.WriteLine("CurrentDate:")DimdtAsDate=TodayConsole.WriteLine("Todayis:{0}",dt)Console.ReadKey()EndSubEndModuleWhentheabovecodeiscompiledandexecuted,itproducesfollowingresult:Todayis:12/11/201212:00:00AMFormattingDateADateliteralshouldbeenclosedwithinhashsigns(##),andspecifiedintheformatM/d/yyyy,forexample#12/16/2012#.Otherwise,yourcodemaychangedependingonthelocaleinwhichyourapplicationisrunning.Forexample,youspecifiedDateliteralof#2/6/2012#forthedateFebruary6,2012.Itisalrightforthelocalethatusesmm/dd/yyyyformat.However,inalocalethatusesdd/mm/yyyyformat,yourliteralwouldcompiletoJune2,2012.Ifalocaleusesanotherformatsay,yyyy/mm/dd,theliteralwouldbeinvalidandcauseacompilererror.ToconvertaDateliteraltotheformatofyourlocale,ortoacustomformat,usetheFormatfunctionofStringclass,specifyingeitherapredefinedoruser-defineddateformat.Thefollowingexampledemonstratesthis.ModuledateNtimeSubMain()Console.WriteLine("IndiaWinsFreedom:")DimindependenceDayAsNewDate(1947,8,15,0,0,0)'Useformatspecifierstocontrolthedatedisplay.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()EndSubEndModuleWhentheabovecodeiscompiledandexecuted,itproducesfollowingresult:

IndiaWinsFreedom:Format'd:'8/15/1947Format'D:'Friday,August15,1947Format't:'12:00AMFormat'T:'12:00:00AMFormat'f:'Friday,August15,194712:00AMFormat'F:'Friday,August15,194712:00:00AMFormat'g:'8/15/194712:00AMFormat'G:'8/15/194712:00:00AMFormat'M:'8/15/1947August15Format'R:'Fri,15August194700:00:00GMTFormat'y:'August,1947PredefinedDate/TimeFormatsThefollowingtableidentifiesthepredefineddateandtimeformatnames.ThesemaybeusedbynameasthestyleargumentfortheFormatfunction:FormatDescriptionGeneralDate,orGDisplaysadateand/ortime.Forexample,1/12/201207:07:30AM.LongDate,MediumDate,orDDisplaysadateaccordingtoyourcurrentculture'slongdateformat.Forexample,Sunday,December16,2012.ShortDate,ordDisplaysadateusingyourcurrentculture'sshortdateformat.Forexample,12/12/2012.LongTime,MediumTime,orTDisplaysatimeusingyourcurrentculture'slongtimeformat;typicallyincludeshours,minutes,seconds.Forexample,01:07:30AM.ShortTimeortDisplaysatimeusingyourcurrentculture'sshorttimeformat.Forexample,11:07AM.fDisplaysthelongdateandshorttimeaccordingtoyourcurrentculture'sformat.Forexample,Sunday,December16,201212:15AM.FDisplaysthelongdateandlongtimeaccordingtoyourcurrentculture'sformat.Forexample,Sunday,December16,201212:15:31AM.gDisplaystheshortdateandshorttimeaccordingtoyourcurrentculture'sformat.Forexample,12/16/201212:15AM.M,mDisplaysthemonthandthedayofadate.Forexample,December16.R,rFormatsthedateaccordingtotheRFC1123Patternproperty.sFormatsthedateandtimeasasortableindex.Forexample,2012-12-16T12:07:31.uFormatsthedateandtimeasaGMTsortableindex.Forexample,2012-12-1612:15:31Z.UFormatsthedateandtimewiththelongdateandlongtimeasGMT.Forexample,Sunday,December16,20126:07:31PM.Y,yFormatsthedateastheyearandmonth.Forexample,December,2012.

Forotherformatslike,userdefinedformats,pleaseconsultMicrosoftDocumentation.PropertiesandMethodsoftheDateAndTimeClassThefollowingtablelistssomeofthecommonlyusedpropertiesoftheDateAndTimeClass:S.NPropertyDescription1DateReturnsorsetsaStringvaluerepresentingthecurrentdateaccordingtoyoursystem.2NowReturnsaDatevaluecontainingthecurrentdateandtimeaccordingtoyoursystem.3TimeOfDayReturnsorsetsaDatevaluecontainingthecurrenttimeofdayaccordingtoyoursystem.4TimerReturnsaDoublevaluerepresentingthenumberofsecondselapsedsincemidnight.5TimeStringReturnsorsetsaStringvaluerepresentingthecurrenttimeofdayaccordingtoyoursystem.6TodayGetsthecurrentdate.ThefollowingtablelistssomeofthecommonlyusedmethodsoftheDateAndTimeclass:S.NMethodName&Description1PublicSharedFunctionDateAdd(IntervalAsDateInterval,NumberAsDouble,DateValueAsDateTime)AsDateTimeReturnsaDatevaluecontainingadateandtimevaluetowhichaspecifiedtimeintervalhasbeenadded.2PublicSharedFunctionDateAdd(IntervalAsString,NumberAsDouble,DateValueAsObject)AsDateTimeReturnsaDatevaluecontainingadateandtimevaluetowhichaspecifiedtimeintervalhasbeenadded.3PublicSharedFunctionDateDiff(IntervalAsDateInterval,Date1AsDateTime,Date2AsDateTime,DayOfWeekAsFirstDayOfWeek,WeekOfYearAsFirstWeekOfYear)AsLongReturnsaLongvaluespecifyingthenumberoftimeintervalsbetweentwoDatevalues.4PublicSharedFunctionDatePart(IntervalAsDateInterval,DateValueAsDateTime,FirstDayOfWeekValueAsFirstDayOfWeek,FirstWeekOfYearValueAsFirstWeekOfYear)AsIntegerReturnsanIntegervaluecontainingthespecifiedcomponentofagivenDatevalue.5PublicSharedFunctionDay(DateValueAsDateTime)AsIntegerReturnsanIntegervaluefrom1through31representingthedayofthemonth.6PublicSharedFunctionHour(TimeValueAsDateTime)AsIntegerReturnsanIntegervaluefrom0through23representingthehouroftheday.7PublicSharedFunctionMinute(TimeValueAsDateTime)AsInteger

ReturnsanIntegervaluefrom0through59representingtheminuteofthehour.8PublicSharedFunctionMonth(DateValueAsDateTime)AsIntegerReturnsanIntegervaluefrom1through12representingthemonthoftheyear.9PublicSharedFunctionMonthName(MonthAsInteger,AbbreviateAsBoolean)AsStringReturnsaStringvaluecontainingthenameofthespecifiedmonth.10PublicSharedFunctionSecond(TimeValueAsDateTime)AsIntegerReturnsanIntegervaluefrom0through59representingthesecondoftheminute.11PublicOverridableFunctionToStringAsStringReturnsastringthatrepresentsthecurrentobject.12PublicSharedFunctionWeekday(DateValueAsDateTime,DayOfWeekAsFirstDayOfWeek)AsIntegerReturnsanIntegervaluecontaininganumberrepresentingthedayoftheweek.13PublicSharedFunctionWeekdayName(WeekdayAsInteger,AbbreviateAsBoolean,FirstDayOfWeekValueAsFirstDayOfWeek)AsStringReturnsaStringvaluecontainingthenameofthespecifiedweekday.14PublicSharedFunctionYear(DateValueAsDateTime)AsIntegerReturnsanIntegervaluefrom1through9999representingtheyear.Theabovelistisnotexhaustive.ForcompletelistofpropertiesandmethodsoftheDateAndTimeclass,pleaseconsultMicrosoftDocumentation.Thefollowingprogramdemonstratessomeoftheseandmethods:ModuleModule1SubMain()DimbirthdayAsDateDimbdayAsIntegerDimmonthAsIntegerDimmonthnameAsString'Assignadateusingstandardshortformat.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()EndSubEndModuleWhentheabovecodeiscompiledandexecuted,itproducesfollowingresult:7/27/199812:00:00AM277JulyVB.NET-ARRAYS

TodeclareanarrayinVB.Net,youusetheDimstatement.Forexample,DimintData(30)'anarrayof31elementsDimstrData(20)AsString'anarrayof21stringsDimtwoDarray(10,20)AsInteger'atwodimensionalarrayofintegersDimranges(10,100)'atwodimensionalarrayYoucanalsoinitializethearrayelementswhiledeclaringthearray.Forexample,DimintData()AsInteger={12,16,20,24,28,32}Dimnames()AsString={"Karthik","Sandhya",_"Shivangi","Ashwitha","Somnath"}DimmiscData()AsObject={"HelloWorld",12d,16ui,"A"c}Theelementsinanarraycanbestoredandaccessedbyusingtheindexofthearray.Thefollowingprogramdemonstratesthis:ModulearrayAplSubMain()Dimn(10)AsInteger'nisanarrayof10integers'Dimi,jAsInteger'initializeelementsofarrayn'Fori=0To10n(i)=i+100'setelementatlocationitoi+100Nexti'outputeacharrayelement'svalue'Forj=0To10Console.WriteLine("Element({0})={1}",j,n(j))NextjConsole.ReadKey()EndSubEndModuleWhentheabovecodeiscompiledandexecuted,itproducesfollowingresult:Element(0)=100Element(1)=101Element(2)=102Element(3)=103Element(4)=104Element(5)=105Element(6)=106Element(7)=107Element(8)=108Element(9)=109Element(10)=110DynamicArraysDynamicarraysarearraysthatcanbedimensionedandre-dimensionedaspartheneedoftheprogram.YoucandeclareadynamicarrayusingtheReDimstatement.SyntaxforReDimstatement:ReDim[Preserve]arrayname(subscripts)Where,ThePreservekeywordhelpstopreservethedatainanexistingarray,whenyouresizeit.arraynameisthenameofthearraytore-dimensionsubscriptsspecifiesthenewdimension.

ModulearrayAplSubMain()Dimmarks()AsIntegerReDimmarks(2)marks(0)=85marks(1)=75marks(2)=90ReDimPreservemarks(10)marks(3)=80marks(4)=76marks(5)=92marks(6)=99marks(7)=79marks(8)=75Fori=0To10Console.WriteLine(i&vbTab&marks(i))NextiConsole.ReadKey()EndSubEndModuleWhentheabovecodeiscompiledandexecuted,itproducesfollowingresult:08517529038047659269977987590100Multi-DimensionalArraysVB.Netallowsmultidimensionalarrays.Multi-dimensionalarraysarealsocalledrectangulararray.Youcandeclarea2dimensionalarrayofstringsas:DimtwoDStringArray(10,20)AsStringor,athreedimensionalarrayofIntegervariables:DimthreeDIntArray(10,10,10)AsIntegerThefollowingprogramdemonstratescreatingandusingatwodimensionalarray:ModulearrayAplSubMain()'anarraywith5rowsand2columnsDima(,)AsInteger={{0,0},{1,2},{2,4},{3,6},{4,8}}Dimi,jAsInteger'outputeacharrayelement'svalue'Fori=0To4Forj=0To1Console.WriteLine("a[{0},{1}]={2}",i,j,a(i,j))NextjNextiConsole.ReadKey()EndSubEndModuleWhentheabovecodeiscompiledandexecuted,itproducesfollowingresult:

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]:8JaggedArrayAJaggedarrayisanarrayofarrays.ThefollwoingcodeshowsdeclaringajaggedarraynamedscoresofIntegers:DimscoresAsInteger()()=NewInteger(5)(){}Thefollowingexampleillustratesusingajaggedarray:ModulearrayAplSubMain()'ajaggedarrayof5arrayofintegersDimaAsInteger()()=NewInteger(4)(){}a(0)=NewInteger(){0,0}a(1)=NewInteger(){1,2}a(2)=NewInteger(){2,4}a(3)=NewInteger(){3,6}a(4)=NewInteger(){4,8}Dimi,jAsInteger'outputeacharrayelement'svalueFori=0To4Forj=0To1Console.WriteLine("a[{0},{1}]={2}",i,j,a(i)(j))NextjNextiConsole.ReadKey()EndSubEndModuleWhentheabovecodeiscompiledandexecuted,itproducesfollowingresult: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]:8TheArrayClassTheArrayclassisthebaseclassforallthearraysinVB.Net.ItisdefinedintheSystemnamespace.TheArrayclassprovidesvariouspropertiesandmethodstoworkwitharrays.PropertiesoftheArrayClassThefollowingtableprovidessomeofthemostcommonlyusedpropertiesoftheArrayclass:S.NPropertyName&Description

1IsFixedSizeGetsavalueindicatingwhethertheArrayhasafixedsize.2IsReadOnlyGetsavalueindicatingwhethertheArrayisread-only.3LengthGetsa32-bitintegerthatrepresentsthetotalnumberofelementsinallthedimensionsoftheArray.4LongLengthGetsa64-bitintegerthatrepresentsthetotalnumberofelementsinallthedimensionsoftheArray.5RankGetstherank(numberofdimensions)oftheArray.MethodsoftheArrayClassThefollowingtableprovidessomeofthemostcommonlyusedmethodsoftheArrayclass:S.NMethodName&Description1PublicSharedSubClear(arrayAsArray,indexAsInteger,lengthAsInteger)SetsarangeofelementsintheArraytozero,tofalse,ortonull,dependingontheelementtype.2PublicSharedSubCopy(sourceArrayAsArray,destinationArrayAsArray,lengthAsInteger)CopiesarangeofelementsfromanArraystartingatthefirstelementandpastesthemintoanotherArraystartingatthefirstelement.Thelengthisspecifiedasa32-bitinteger.3PublicSubCopyTo(arrayAsArray,indexAsInteger)Copiesalltheelementsofthecurrentone-dimensionalArraytothespecifiedone-dimensionalArraystartingatthespecifieddestinationArrayindex.Theindexisspecifiedasa32-bitinteger.4PublicFunctionGetLength(dimensionAsInteger)AsIntegerGetsa32-bitintegerthatrepresentsthenumberofelementsinthespecifieddimensionoftheArray.5PublicFunctionGetLongLength(dimensionAsInteger)AsLongGetsa64-bitintegerthatrepresentsthenumberofelementsinthespecifieddimensionoftheArray.6PublicFunctionGetLowerBound(dimensionAsInteger)AsIntegerGetsthelowerboundofthespecifieddimensionintheArray.7PublicFunctionGetTypeAsTypeGetstheTypeofthecurrentinstance.(InheritedfromObject.)8PublicFunctionGetUpperBound(dimensionAsInteger)AsIntegerGetstheupperboundofthespecifieddimensionintheArray.9PublicFunctionGetValue(indexAsInteger)AsObjectGetsthevalueatthespecifiedpositionintheone-dimensionalArray.Theindexisspecifiedasa32-bitinteger.10PublicSharedFunctionIndexOf(arrayAsArray,valueAsObject)AsInteger

Searchesforthespecifiedobjectandreturnstheindexofthefirstoccurrencewithintheentireone-dimensionalArray.11PublicSharedSubReverse(arrayAsArray)Reversesthesequenceoftheelementsintheentireone-dimensionalArray.12PublicSubSetValue(valueAsObject,indexAsInteger)Setsavaluetotheelementatthespecifiedpositionintheone-dimensionalArray.Theindexisspecifiedasa32-bitinteger.13PublicSharedSubSort(arrayAsArray)Sortstheelementsinanentireone-dimensionalArrayusingtheIComparableimplementationofeachelementoftheArray.14PublicOverridableFunctionToStringAsStringeturnsastringthatrepresentsthecurrentobject.(InheritedfromObject.)ForcompletelistofArrayclasspropertiesandmethods,pleaseconsultMicrosoftdocumentation.ExampleThefollowingprogramdemonstratesuseofsomeofthemethodsoftheArrayclass:ModulearrayAplSubMain()DimlistAsInteger()={34,72,13,44,25,30,10}DimtempAsInteger()=listDimiAsIntegerConsole.Write("OriginalArray:")ForEachiInlistConsole.Write("{0}",i)NextiConsole.WriteLine()'reversethearrayArray.Reverse(temp)Console.Write("ReversedArray:")ForEachiIntempConsole.Write("{0}",i)NextiConsole.WriteLine()'sortthearrayArray.Sort(list)Console.Write("SortedArray:")ForEachiInlistConsole.Write("{0}",i)NextiConsole.WriteLine()Console.ReadKey()EndSubEndModuleWhentheabovecodeiscompiledandexecuted,itproducesfollowingresult:OriginalArray:34721344253010ReversedArray:10302544137234SortedArray:10132530344472VB.NET-COLLECTIONSCollectionclassesarespecializedclassesfordatastorageandretrieval.Theseclassesprovidesupportforstacks,queues,

lists,andhashtables.Mostcollectionclassesimplementthesameinterfaces.Collectionclassesservevariouspurposes,suchasallocatingmemorydynamicallytoelementsandaccessingalistofitemsonthebasisofanindexetc.TheseclassescreatecollectionsofobjectsoftheObjectclass,whichisthebaseclassforalldatatypesinC#.VariousCollectionClassesandTheirUsageThefollowingarethevariouscommonlyusedclassesoftheSystem.Collectionnamespace.Clickthefollowinglinkstochecktheirdetail.ClassDescriptionandUseageArrayListItrepresentsorderedcollectionofanobjectthatcanbeindexedindividually.Itisbasicallyanalternativetoanarray.Howeverunlikearrayyoucanaddandremoveitemsfromalistataspecifiedpositionusinganindexandthearrayresizesitselfautomatically.Italsoallowsdynamicmemoryallocation,add,searchandsortitemsinthelist.HashtableItusesakeytoaccesstheelementsinthecollection.Ahashtableisusedwhenyouneedtoaccesselementsbyusingkey,andyoucanidentifyausefulkeyvalue.Eachiteminthehashtablehasakey/valuepair.Thekeyisusedtoaccesstheitemsinthecollection.SortedListItusesakeyaswellasanindextoaccesstheitemsinalist.Asortedlistisacombinationofanarrayandahashtable.Itcontainsalistofitemsthatcanbeaccessedusingakeyoranindex.Ifyouaccessitemsusinganindex,itisanArrayList,andifyouaccessitemsusingakey,itisaHashtable.Thecollectionofitemsisalwayssortedbythekeyvalue.StackItrepresentsalast-in,firstoutcollectionofobject.Itisusedwhenyouneedalast-in,first-outaccessofitems.Whenyouaddaniteminthelist,itiscalledpushingtheitemandwhenyouremoveit,itiscalledpoppingtheitem.QueueItrepresentsafirst-in,firstoutcollectionofobject.Itisusedwhenyouneedafirst-in,first-outaccessofitems.Whenyouaddaniteminthelist,itiscalledenqueueandwhenyouremoveanitem,itiscalleddeque.BitArrayItrepresentsanarrayofthebinaryrepresentationusingthevalues1and0.Itisusedwhenyouneedtostorethebitsbutdonotknowthenumberofbitsinadvance.YoucanaccessitemsfromtheBitArraycollectionbyusinganintegerindex,whichstartsfromzero.

VB.NET-FUNCTIONSAprocedureisagroupofstatementsthattogetherperformatask,whencalled.Aftertheprocedureisexecuted,thecontrolreturnstothestatementcallingtheprocedure.VB.Nethastwotypesofprocedures:FunctionsSubproceduresorSubsFunctionsreturnavalue,whereSubsdonotreturnavalue.DefiningaFunctionTheFunctionstatementisusedtodeclarethename,parameterandthebodyofafunction.ThesyntaxfortheFunctionstatementis:[Modifiers]FunctionFunctionName[(ParameterList)]AsReturnType[Statements]EndFunctionWhere,Tutorialcontentgoeshere.....Modifiers:specifiytheaccesslevelofthefunction;possiblevaluesare:Public,Private,Protected,Friend,ProtectedFriendandinformationregardingoverloading,overriding,sharing,andshadowing.FunctionName:indicatesthenameofthefunctionParameterList:specifiesthelistoftheparametersReturnType:specifiesthedatatypeofthevariablethefunctionreturnsExampleFollowingcodesnippetshowsafunctionFindMaxthattakestwointegervaluesandreturnsthelargerofthetwo.FunctionFindMax(ByValnum1AsInteger,ByValnum2AsInteger)AsInteger'localvariabledeclaration*/DimresultAsIntegerIf(num1>num2)Thenresult=num1Elseresult=num2EndIfFindMax=resultEndFunctionFunctionReturningaValueInVB.Netafunctioncanreturnavaluetothecallingcodeintwoways:ByusingthereturnstatementByassigningthevaluetothefunctionnameThefollowingexampledemonstratesusingtheFindMaxfunction:

ModulemyfunctionsFunctionFindMax(ByValnum1AsInteger,ByValnum2AsInteger)AsInteger'localvariabledeclaration*/DimresultAsIntegerIf(num1>num2)Thenresult=num1Elseresult=num2EndIfFindMax=resultEndFunctionSubMain()DimaAsInteger=100DimbAsInteger=200DimresAsIntegerres=FindMax(a,b)Console.WriteLine("Maxvalueis:{0}",res)Console.ReadLine()EndSubEndModuleWhentheabovecodeiscompiledandexecuted,itproducesfollowingresult:Maxvalueis:200RecursiveFunctionAfunctioncancallitself.Thisisknownasrecursion.Followingisanexamplethatcalculatesfactorialforagivennumberusingarecursivefunction:ModulemyfunctionsFunctionfactorial(ByValnumAsInteger)AsInteger'localvariabledeclaration*/DimresultAsIntegerIf(num=1)ThenReturn1Elseresult=factorial(num-1)*numReturnresultEndIfEndFunctionSubMain()'callingthefactorialmethodConsole.WriteLine("Factorialof6is:{0}",factorial(6))Console.WriteLine("Factorialof7is:{0}",factorial(7))Console.WriteLine("Factorialof8is:{0}",factorial(8))Console.ReadLine()EndSubEndModuleWhentheabovecodeiscompiledandexecuted,itproducesfollowingresult:Factorialof6is:720Factorialof7is:5040Factorialof8is:40320ParamArraysAttimes,whiledeclaringafunctionorsubprocedureyouarenotsureofthenumberofargumentspassedasaparameter.VB.Netparamarrays(orparameterarrays)comeintohelpatthesetimes.Thefollowingexampledemonstratesthis:Modulemyparamfunc

FunctionAddElements(ParamArrayarrAsInteger())AsIntegerDimsumAsInteger=0DimiAsInteger=0ForEachiInarrsum+=iNextiReturnsumEndFunctionSubMain()DimsumAsIntegersum=AddElements(512,720,250,567,889)Console.WriteLine("Thesumis:{0}",sum)Console.ReadLine()EndSubEndModuleWhentheabovecodeiscompiledandexecuted,itproducesfollowingresult:Thesumis:2938PassingArraysasFunctionArgumentsYoucanpassanarrayasafunctionargumentinVB.Net.Thefollowingexampledemonstratesthis:ModulearrayParameterFunctiongetAverage(ByValarrAsInteger(),ByValsizeAsInteger)AsDouble'localvariablesDimiAsIntegerDimavgAsDoubleDimsumAsInteger=0Fori=0Tosize-1sum+=arr(i)Nextiavg=sum/sizeReturnavgEndFunctionSubMain()'anintarraywith5elements'DimbalanceAsInteger()={1000,2,3,17,50}DimavgAsDouble'passpointertothearrayasanargumentavg=getAverage(balance,5)'outputthereturnedvalue'Console.WriteLine("Averagevalueis:{0}",avg)Console.ReadLine()EndSubEndModuleWhentheabovecodeiscompiledandexecuted,itproducesfollowingresult:Averagevalueis:214.4VB.NET-SUBPROCEDURESAswementionedinthepreviouschapter,Subproceduresareproceduresthatdonotreturnanyvalue.WehavebeenusingtheSubprocedureMaininallourexamples.Wehavebeenwritingconsoleapplicationssofar,inthesetutorials.Whentheseapplicationsstart,thecontrolgoestotheMainSubprocedure,anditinturn,runsanyotherstatementsconstitutingthebodyoftheprogram.DefiningSubProceduresTheSubstatementisusedtodeclarethename,parameterandthebodyofasubprocedure.ThesyntaxfortheSubstatementis:

[Modifiers]SubSubName[(ParameterList)][Statements]EndSubWhere,Modifiers:specifiytheaccessleveloftheprocedure;possiblevaluesare:Public,Private,Protected,Friend,ProtectedFriendandinformationregardingoverloading,overriding,sharing,andshadowing.SubName:indicatesthenameoftheSubParameterList:specifiesthelistoftheparametersExampleThefollowingexampledemonstratesaSubprocedureCalculatePaythattakestwoparametershoursandwagesanddisplaysthetotalpayofanemployee:ModulemysubSubCalculatePay(ByValhoursAsDouble,ByValwageAsDecimal)'localvariabledeclarationDimpayAsDoublepay=hours*wageConsole.WriteLine("TotalPay:{0:C}",pay)EndSubSubMain()'callingtheCalculatePaySubProcedureCalculatePay(25,10)CalculatePay(40,20)CalculatePay(30,27.5)Console.ReadLine()EndSubEndModuleWhentheabovecodeiscompiledandexecuted,itproducesfollowingresult:TotalPay:$250.00TotalPay:$800.00TotalPay:$825.00PassingParametersbyValueThisisthedefaultmechanismforpassingparameterstoamethod.Inthismechanism,whenamethodiscalled,anewstoragelocationiscreatedforeachvalueparameter.Thevaluesoftheactualparametersarecopiedintothem.So,thechangesmadetotheparameterinsidethemethodhavenoeffectontheargument.InVB.Net,youdeclarethereferenceparametersusingtheByValkeyword.Thefollowingexampledemonstratestheconcept:ModuleparamByvalSubswap(ByValxAsInteger,ByValyAsInteger)DimtempAsIntegertemp=x'savethevalueofxx=y'putyintoxy=temp'puttempintoyEndSubSubMain()'localvariabledefinitionDimaAsInteger=100DimbAsInteger=200Console.WriteLine("Beforeswap,valueofa:{0}",a)Console.WriteLine("Beforeswap,valueofb:{0}",b)'callingafunctiontoswapthevalues'

swap(a,b)Console.WriteLine("Afterswap,valueofa:{0}",a)Console.WriteLine("Afterswap,valueofb:{0}",b)Console.ReadLine()EndSubEndModuleWhentheabovecodeiscompiledandexecuted,itproducesfollowingresult:Beforeswap,valueofa:100Beforeswap,valueofb:200Afterswap,valueofa:100Afterswap,valueofb:200Itshowsthatthereisnochangeinthevaluesthoughtheyhadbeenchangedinsidethefunction.PassingParametersbyReferenceAreferenceparameterisareferencetoamemorylocationofavariable.Whenyoupassparametersbyreference,unlikevalueparameters,anewstoragelocationisnotcreatedfortheseparameters.Thereferenceparametersrepresentthesamememorylocationastheactualparametersthataresuppliedtothemethod.InVB.Net,youdeclarethereferenceparametersusingtheByRefkeyword.Thefollowingexampledemonstratesthis:ModuleparamByrefSubswap(ByRefxAsInteger,ByRefyAsInteger)DimtempAsIntegertemp=x'savethevalueofxx=y'putyintoxy=temp'puttempintoyEndSubSubMain()'localvariabledefinitionDimaAsInteger=100DimbAsInteger=200Console.WriteLine("Beforeswap,valueofa:{0}",a)Console.WriteLine("Beforeswap,valueofb:{0}",b)'callingafunctiontoswapthevalues'swap(a,b)Console.WriteLine("Afterswap,valueofa:{0}",a)Console.WriteLine("Afterswap,valueofb:{0}",b)Console.ReadLine()EndSubEndModuleWhentheabovecodeiscompiledandexecuted,itproducesfollowingresult:Beforeswap,valueofa:100Beforeswap,valueofb:200Afterswap,valueofa:200Afterswap,valueofb:100VB.NET-CLASSES&OBJECTSWhenyoudefineaclass,youdefineablueprintforadatatype.Thisdoesn'tactuallydefineanydata,butitdoesdefinewhattheclassnamemeans,thatis,whatanobjectoftheclasswillconsistofandwhatoperationscanbeperformedonsuchanobject.Objectsareinstancesofaclass.Themethodsandvariablesthatconstituteaclassarecalledmembersoftheclass.ClassDefinition

AclassdefinitionstartswiththekeywordClassfollowedbytheclassname;andtheclassbody,endedbytheEndClassstatement.Followingisthegeneralformofaclassdefinition:[

][accessmodifier][Shadows][MustInherit|NotInheritable][Partial]_Classname[(Oftypelist)][Inheritsclassname][Implementsinterfacenames][statements]EndClassWhere,attributelistisalistofattributesthatapplytotheclass.Optional.accessmodifierdefinestheaccesslevelsoftheclass,ithasvaluesas-Public,Protected,Friend,ProtectedFriendandPrivate.Optional.Shadowsindicatethatthevariablere-declaresandhidesanidenticallynamedelement,orsetofoverloadedelements,inabaseclass.Optional.MustInheritspecifiesthattheclasscanbeusedonlyasabaseclassandthatyoucannotcreateanobjectdirectlyfromit,i.e,anabstractclass.Optional.NotInheritablespecifiesthattheclasscannotbeusedasabaseclass.PartialindicatesapartialdefinitionoftheclassInheritsspecifiesthebaseclassitisinheritingfromImplementsspecifiestheinterfacestheclassisinheritingfromThefollowingexampledemonstratesaBoxclass,withthreedatamembers,length,breadthandheight:ModulemyboxClassBoxPubliclengthAsDouble'LengthofaboxPublicbreadthAsDouble'BreadthofaboxPublicheightAsDouble'HeightofaboxEndClassSubMain()DimBox1AsBox=NewBox()'DeclareBox1oftypeBoxDimBox2AsBox=NewBox()'DeclareBox2oftypeBoxDimvolumeAsDouble=0.0'Storethevolumeofaboxhere'box1specificationBox1.height=5.0Box1.length=6.0Box1.breadth=7.0'box2specificationBox2.height=10.0Box2.length=12.0Box2.breadth=13.0'volumeofbox1volume=Box1.height*Box1.length*Box1.breadthConsole.WriteLine("VolumeofBox1:{0}",volume)'volumeofbox2volume=Box2.height*Box2.length*Box2.breadthConsole.WriteLine("VolumeofBox2:{0}",volume)Console.ReadKey()EndSubEndModuleWhentheabovecodeiscompiledandexecuted,itproducesfollowingresult:

VolumeofBox1:210VolumeofBox2:1560MemberFunctionsandEncapsulationAmemberfunctionofaclassisafunctionthathasitsdefinitionoritsprototypewithintheclassdefinitionlikeanyothervariable.Itoperatesonanyobjectoftheclassofwhichitisamember,andhasaccesstoallthemembersofaclassforthatobject.Membervariablesareattributesofanobject(fromdesignperspective)andtheyarekeptprivatetoimplementencapsulation.Thesevariablescanonlybeaccessedusingthepublicmemberfunctions.Letusputaboveconceptstosetandgetthevalueofdifferentclassmembersinaclass:ModulemyboxClassBoxPubliclengthAsDouble'LengthofaboxPublicbreadthAsDouble'BreadthofaboxPublicheightAsDouble'HeightofaboxPublicSubsetLength(ByVallenAsDouble)length=lenEndSubPublicSubsetBreadth(ByValbreAsDouble)breadth=breEndSubPublicSubsetHeight(ByValheiAsDouble)height=heiEndSubPublicFunctiongetVolume()AsDoubleReturnlength*breadth*heightEndFunctionEndClassSubMain()DimBox1AsBox=NewBox()'DeclareBox1oftypeBoxDimBox2AsBox=NewBox()'DeclareBox2oftypeBoxDimvolumeAsDouble=0.0'Storethevolumeofaboxhere'box1specificationBox1.setLength(6.0)Box1.setBreadth(7.0)Box1.setHeight(5.0)'box2specificationBox2.setLength(12.0)Box2.setBreadth(13.0)Box2.setHeight(10.0)'volumeofbox1volume=Box1.getVolume()Console.WriteLine("VolumeofBox1:{0}",volume)'volumeofbox2volume=Box2.getVolume()Console.WriteLine("VolumeofBox2:{0}",volume)Console.ReadKey()EndSubEndModuleWhentheabovecodeiscompiledandexecuted,itproducesfollowingresult:VolumeofBox1:210VolumeofBox2:1560ConstructorsandDestructorsAclassconstructorisaspecialmemberSubofaclassthatisexecutedwheneverwecreatenewobjectsofthatclass.A

constructorhasthenameNewanditdoesnothaveanyreturntype.Followingprogramexplaintheconceptofconstructor:ClassLinePrivatelengthAsDouble'LengthofalinePublicSubNew()'constructorConsole.WriteLine("Objectisbeingcreated")EndSubPublicSubsetLength(ByVallenAsDouble)length=lenEndSubPublicFunctiongetLength()AsDoubleReturnlengthEndFunctionSharedSubMain()DimlineAsLine=NewLine()'setlinelengthline.setLength(6.0)Console.WriteLine("Lengthofline:{0}",line.getLength())Console.ReadKey()EndSubEndClassWhentheabovecodeiscompiledandexecuted,itproducesfollowingresult:ObjectisbeingcreatedLengthofline:6Adefaultconstructordoesnothaveanyparameterbutifyouneedaconstructorcanhaveparameters.Suchconstructorsarecalledparameterizedconstructors.Thistechniquehelpsyoutoassigninitialvaluetoanobjectatthetimeofitscreationasshowninthefollowingexample:ClassLinePrivatelengthAsDouble'LengthofalinePublicSubNew(ByVallenAsDouble)'parameterisedconstructorConsole.WriteLine("Objectisbeingcreated,length={0}",len)length=lenEndSubPublicSubsetLength(ByVallenAsDouble)length=lenEndSubPublicFunctiongetLength()AsDoubleReturnlengthEndFunctionSharedSubMain()DimlineAsLine=NewLine(10.0)Console.WriteLine("Lengthoflinesetbyconstructor:{0}",line.getLength())'setlinelengthline.setLength(6.0)Console.WriteLine("LengthoflinesetbysetLength:{0}",line.getLength())Console.ReadKey()EndSubEndClassWhentheabovecodeiscompiledandexecuted,itproducesfollowingresult:Objectisbeingcreated,length=10Lengthoflinesetbyconstructor:10LengthoflinesetbysetLength:6AdestructorisaspecialmemberSubofaclassthatisexecutedwheneveranobjectofitsclassgoesoutofscope.

AdestructorhasthenameFinalizeanditcanneitherreturnavaluenorcanittakeanyparameters.Destructorcanbeveryusefulforreleasingresourcesbeforecomingoutoftheprogramlikeclosingfiles,releasingmemoriesetc.Destructorscannotbeinheritedoroverloaded.Followingexampleexplaintheconceptofdestructor:ClassLinePrivatelengthAsDouble'LengthofalinePublicSubNew()'parameterisedconstructorConsole.WriteLine("Objectisbeingcreated")EndSubProtectedOverridesSubFinalize()'destructorConsole.WriteLine("Objectisbeingdeleted")EndSubPublicSubsetLength(ByVallenAsDouble)length=lenEndSubPublicFunctiongetLength()AsDoubleReturnlengthEndFunctionSharedSubMain()DimlineAsLine=NewLine()'setlinelengthline.setLength(6.0)Console.WriteLine("Lengthofline:{0}",line.getLength())Console.ReadKey()EndSubEndClassWhentheabovecodeiscompiledandexecuted,itproducesfollowingresult:ObjectisbeingcreatedLengthofline:6ObjectisbeingdeletedSharedMembersofaVB.NetClassWecandefineclassmembersasstaticusingtheSharedkeyword.WhenwedeclareamemberofaclassasShareditmeansnomatterhowmanyobjectsoftheclassarecreated,thereisonlyonecopyofthemember.ThekeywordSharedimpliesthatonlyoneinstanceofthememberexistsforaclass.Sharedvariablesareusedfordefiningconstantsbecausetheirvaluescanberetrievedbyinvokingtheclasswithoutcreatinganinstanceofit.Sharedvariablescanbeinitializedoutsidethememberfunctionorclassdefinition.YoucanalsoinitializeSharedvariablesinsidetheclassdefinition.YoucanalsodeclareamemberfunctionasShared.SuchfunctionscanaccessonlySharedvariables.TheSharedfunctionsexistevenbeforetheobjectiscreated.Thefollowingexampledemonstratestheuseofsharedmembers:ClassStaticVarPublicSharednumAsIntegerPublicSubcount()num=num+1EndSubPublicSharedFunctiongetNum()AsIntegerReturnnumEndFunctionSharedSubMain()DimsAsStaticVar=NewStaticVar()s.count()s.count()

s.count()Console.WriteLine("Valueofvariablenum:{0}",StaticVar.getNum())Console.ReadKey()EndSubEndClassWhentheabovecodeiscompiledandexecuted,itproducesfollowingresult:Valueofvariablenum:3InheritanceOneofthemostimportantconceptsinobject-orientedprogrammingisthatofinheritance.Inheritanceallowsustodefineaclassintermsofanotherclass,whichmakesiteasiertocreateandmaintainanapplication.Thisalsoprovidesanopportunitytoreusethecodefunctionalityandfastimplementationtime.Whencreatingaclass,insteadofwritingcompletelynewdatamembersandmemberfunctions,theprogrammercandesignatethatthenewclassshouldinheritthemembersofanexistingclass.Thisexistingclassiscalledthebaseclass,andthenewclassisreferredtoasthederivedclass.Base&DerivedClasses:Aclasscanbederivedfrommorethanoneclassorinterface,whichmeansthatitcaninheritdataandfunctionsfrommultiplebaseclassorinterface.ThesyntaxusedinVB.Netforcreatingderivedclassesisasfollows:

Class

...EndClassClass:Inherits

...EndClassConsiderabaseclassShapeanditsderivedclassRectangle:'BaseclassClassShapeProtectedwidthAsIntegerProtectedheightAsIntegerPublicSubsetWidth(ByValwAsInteger)width=wEndSubPublicSubsetHeight(ByValhAsInteger)height=hEndSubEndClass'DerivedclassClassRectangle:InheritsShapePublicFunctiongetArea()AsIntegerReturn(width*height)EndFunctionEndClassClassRectangleTesterSharedSubMain()DimrectAsRectangle=NewRectangle()rect.setWidth(5)rect.setHeight(7)'Printtheareaoftheobject.Console.WriteLine("Totalarea:{0}",rect.getArea())Console.ReadKey()EndSubEndClass

Whentheabovecodeiscompiledandexecuted,itproducesfollowingresult:Totalarea:35BaseClassInitializationThederivedclassinheritsthebaseclassmembervariablesandmembermethods.Thereforethesuperclassobjectshouldbecreatedbeforethesubclassiscreated.ThesuperclassorthebaseclassisimplicitlyknownasMyBaseinVB.NetThefollowingprogramdemonstratesthis:'BaseclassClassRectangleProtectedwidthAsDoubleProtectedlengthAsDoublePublicSubNew(ByVallAsDouble,ByValwAsDouble)length=lwidth=wEndSubPublicFunctionGetArea()AsDoubleReturn(width*length)EndFunctionPublicOverridableSubDisplay()Console.WriteLine("Length:{0}",length)Console.WriteLine("Width:{0}",width)Console.WriteLine("Area:{0}",GetArea())EndSub'endclassRectangleEndClass'DerivedclassClassTabletop:InheritsRectanglePrivatecostAsDoublePublicSubNew(ByVallAsDouble,ByValwAsDouble)MyBase.New(l,w)EndSubPublicFunctionGetCost()AsDoubleDimcostAsDoublecost=GetArea()*70ReturncostEndFunctionPublicOverridesSubDisplay()MyBase.Display()Console.WriteLine("Cost:{0}",GetCost())EndSub'endclassTabletopEndClassClassRectangleTesterSharedSubMain()DimtAsTabletop=NewTabletop(4.5,7.5)t.Display()Console.ReadKey()EndSubEndClassWhentheabovecodeiscompiledandexecuted,itproducesfollowingresult:Length:4.5Width:7.5Area:33.75Cost:2362.5VB.Netsupportsmultipleinheritance.VB.NET-EXCEPTIONHANDLING

Anexceptionisaproblemthatarisesduringtheexecutionofaprogram.Anexceptionisaresponsetoanexceptionalcircumstancethatariseswhileaprogramisrunning,suchasanattempttodividebyzero.Exceptionsprovideawaytotransfercontrolfromonepartofaprogramtoanother.VB.Netexceptionhandlingisbuiltuponfourkeywords:Try,Catch,FinallyandThrow.Try:ATryblockidentifiesablockofcodeforwhichparticularexceptionswillbeactivated.It'sfollowedbyoneormoreCatchblocks.Catch:Aprogramcatchesanexceptionwithanexceptionhandlerattheplaceinaprogramwhereyouwanttohandletheproblem.TheCatchkeywordindicatesthecatchingofanexception.Finally:TheFinallyblockisusedtoexecuteagivensetofstatements,whetheranexceptionisthrownornotthrown.Forexample,ifyouopenafile,itmustbeclosedwhetheranexceptionisraisedornot.Throw:Aprogramthrowsanexceptionwhenaproblemshowsup.ThisisdoneusingaThrowkeyword.SyntaxAssumingablockwillraiseandexception,amethodcatchesanexceptionusingacombinationoftheTryandCatchkeywords.ATry/Catchblockisplacedaroundthecodethatmightgenerateanexception.CodewithinaTry/Catchblockisreferredtoasprotectedcode,andthesyntaxforusingTry/Catchlookslikethefollowing:Try[tryStatements][ExitTry][Catch[exception[Astype]][Whenexpression][catchStatements][ExitTry]][Catch...][Finally[finallyStatements]]EndTryYoucanlistdownmultiplecatchstatementstocatchdifferenttypeofexceptionsincaseyourtryblockraisesmorethanoneexceptionindifferentsituations.ExceptionClassesin.NetFrameworkInthe.NetFrameworkexceptionsarerepresentedbyclasses.Theexceptionclassesin.NetFrameworkaremainlydirectlyorindirectlyderivedfromtheSystem.Exceptionclass.SomeoftheexceptionclassesderivedfromtheSystem.ExceptionclassaretheSystem.ApplicationExceptionandSystem.SystemExceptionclasses.TheSystem.ApplicationExceptionclasssupportsexceptionsgeneratedbyapplicationprograms.Sotheexceptionsdefinedbytheprogrammersshouldderivefromthisclass.TheSystem.SystemExceptionclassisthebaseclassforallpredefinedsystemexception.ThefollowingtableprovidessomeofthepredefinedexceptionclassesderivedfromtheSytem.SystemExceptionclass:ExceptionClassDescriptionSystem.IO.IOExceptionHandlesI/Oerrors.System.IndexOutOfRangeExceptionHandleserrorsgeneratedwhenamethodreferstoanarrayindexoutofrange.

System.ArrayTypeMismatchExceptionHandleserrorsgeneratedwhentypeismismatchedwiththearraytype.System.NullReferenceExceptionHandleserrorsgeneratedfromdeferencinganullobject.System.DivideByZeroExceptionHandleserrorsgeneratedfromdividingadividendwithzero.System.InvalidCastExceptionHandleserrorsgeneratedduringtypecasting.System.OutOfMemoryExceptionHandleserrorsgeneratedfrominsufficientfreememory.System.StackOverflowExceptionHandleserrorsgeneratedfromstackoverflow.HandlingExceptionsVB.Netprovidesastructuredsolutiontotheexceptionhandlingproblemsintheformoftryandcatchblocks.Usingtheseblocksthecoreprogramstatementsareseparatedfromtheerror-handlingstatements.TheseerrorhandlingblocksareimplementedusingtheTry,CatchandFinallykeywords.Followingisanexampleofthrowinganexceptionwhendividingbyzeroconditionoccurs:ModuleexceptionProgSubdivision(ByValnum1AsInteger,ByValnum2AsInteger)DimresultAsIntegerTryresult=num1\num2CatcheAsDivideByZeroExceptionConsole.WriteLine("Exceptioncaught:{0}",e)FinallyConsole.WriteLine("Result:{0}",result)EndTryEndSubSubMain()division(25,0)Console.ReadKey()EndSubEndModuleWhentheabovecodeiscompiledandexecuted,itproducesfollowingresult:Exceptioncaught:System.DivideByZeroException:Attemptedtodividebyzero.at...Result:0CreatingUser-DefinedExceptionsYoucanalsodefineyourownexception.UserdefinedexceptionclassesarederivedfromtheApplicationExceptionclass.Thefollowingexampledemonstratesthis:ModuleexceptionProgPublicClassTempIsZeroException:InheritsApplicationExceptionPublicSubNew(ByValmessageAsString)MyBase.New(message)EndSubEndClassPublicClassTemperatureDimtemperatureAsInteger=0SubshowTemp()If(temperature=0)ThenThrow(NewTempIsZeroException("ZeroTemperaturefound"))ElseConsole.WriteLine("Temperature:{0}",temperature)

EndIfEndSubEndClassSubMain()DimtempAsTemperature=NewTemperature()Trytemp.showTemp()CatcheAsTempIsZeroExceptionConsole.WriteLine("TempIsZeroException:{0}",e.Message)EndTryConsole.ReadKey()EndSubEndModuleWhentheabovecodeiscompiledandexecuted,itproducesfollowingresult:TempIsZeroException:ZeroTemperaturefoundThrowingObjectsYoucanthrowanobjectifitiseitherdirectlyorindirectlyderivedfromtheSystem.Exceptionclass.Youcanuseathrowstatementinthecatchblocktothrowthepresentobjectas:Throw[expression]Thefollowingprogramdemonstratesthis:ModuleexceptionProgSubMain()TryThrowNewApplicationException("Acustomexception_isbeingthrownhere...")CatcheAsExceptionConsole.WriteLine(e.Message)FinallyConsole.WriteLine("NowinsidetheFinallyBlock")EndTryConsole.ReadKey()EndSubEndModuleWhentheabovecodeiscompiledandexecuted,itproducesfollowingresult:Acustomexceptionisbeingthrownhere...NowinsidetheFinallyBlockVB.NET-FILEHANDLINGAfileisacollectionofdatastoredinadiskwithaspecificnameandadirectorypath.Whenafileisopenedforreadingorwriting,itbecomesastream.Thestreamisbasicallythesequenceofbytespassingthroughthecommunicationpath.Therearetwomainstreams:theinputstreamandtheoutputstream.Theinputstreamisusedforreadingdatafromfile(readoperation)andtheoutputstreamisusedforwritingintothefile(writeoperation).VB.NetI/OClassesTheSystem.IOnamespacehasvariousclassthatareusedforperformingvariousoperationwithfiles,likecreatinganddeletingfiles,readingfromorwritingtoafile,closingafileetc.

Thefollowingtableshowssomecommonlyusednon-abstractclassesintheSystem.IOnamespace:I/OClassDescriptionBinaryReaderReadsprimitivedatafromabinarystream.BinaryWriterWritesprimitivedatainbinaryformat.BufferedStreamAtemporarystorageforastreamofbytes.DirectoryHelpsinmanipulatingadirectorystructure.DirectoryInfoUsedforperformingoperationsondirectories.DriveInfoProvidesinformationforthedrives.FileHelpsinmanipulatingfiles.FileInfoUsedforperformingoperationsonfiles.FileStreamUsedtoreadfromandwritetoanylocationinafile.MemoryStreamUsedforrandomaccesstostreameddatastoredinmemory.PathPerformsoperationsonpathinformation.StreamReaderUsedforreadingcharactersfromabytestream.StreamWriterIsusedforwritingcharacterstoastream.StringReaderIsusedforreadingfromastringbuffer.StringWriterIsusedforwritingintoastringbuffer.TheFileStreamClassTheFileStreamclassintheSystem.IOnamespacehelpsinreadingfrom,writingtoandclosingfiles.ThisclassderivesfromtheabstractclassStream.YouneedtocreateaFileStreamobjecttocreateanewfileoropenanexistingfile.ThesyntaxforcreatingaFileStreamobjectisasfollows:Dim

AsFileStream=NewFileStream(,,,)Forexample,forcreatingaFileStreamobjectFforreadingafilenamedsample.txt:Dimf1AsFileStream=NewFileStream("test.dat",FileMode.OpenOrCreate,FileAccess.ReadWrite)ParameterDescriptionFileModeTheFileModeenumeratordefinesvariousmethodsforopeningfiles.ThemembersoftheFileModeenumeratorare:

Append:Itopensanexistingfileandputscursorattheendoffile,orcreatesthefile,ifthefiledoesnotexist.Create:Itcreatesanewfile.CreateNew:Itspecifiestotheoperatingsystem,thatitshouldcreateanewfile.Open:Itopensanexistingfile.OpenOrCreate:Itspecifiestotheoperatingsystemthatitshouldopenafileifitexists,otherwiseitshouldcreateanewfile.Truncate:Itopensanexistingfileandtruncatesitssizetozerobytes.FileAccessFileAccessenumeratorshavemembers:Read,ReadWriteandWrite.FileShareFileShareenumeratorshavethefollowingmembers:Inheritable:ItallowsafilehandletopassinheritancetothechildprocessesNone:ItdeclinessharingofthecurrentfileRead:ItallowsopeningthefileforreadingReadWrite:ItallowsopeningthefileforreadingandwritingWrite:ItallowsopeningthefileforwritingExample:ThefollowingprogramdemonstratesuseoftheFileStreamclass:ImportsSystem.IOModulefileProgSubMain()Dimf1AsFileStream=NewFileStream("test.dat",_FileMode.OpenOrCreate,FileAccess.ReadWrite)DimiAsIntegerFori=0To20f1.WriteByte(CByte(i))Nextif1.Position=0Fori=0To20Console.Write("{0}",f1.ReadByte())Nextif1.Close()Console.ReadKey()EndSubEndModuleWhentheabovecodeiscompiledandexecuted,itproducesfollowingresult:1234567891011121314151617181920-1

AdvancedFileOperationsinVB.NetTheprecedingexampleprovidessimplefileoperationsinVB.Net.However,toutilizetheimmensepowersofSystem.IOclasses,youneedtoknowthecommonlyusedpropertiesandmethodsoftheseclasses.Wewilldiscusstheseclassesandtheoperationstheyperform,inthefollowingsections.Pleaseclickthelinksprovidedtogettotheindividualsections:TopicandDescriptionReadingfromandWritingintoTextfilesItinvolvesreadingfromandwritingintotextfiles.TheStreamReaderandStreamWriterclasshelpstoaccomplishit.ReadingfromandWritingintoBinaryfilesItinvolvesreadingfromandwritingintobinaryfiles.TheBinaryReaderandBinaryWriterclasshelpstoaccomplishthis.ManipulatingtheWindowsfilesystemItgivesaVB.NetprogramamertheabilitytobrowseandlocateWindowsfilesanddirectories.VB.NET-BASICCONTROLSAnobjectisatypeofuserinterfaceelementyoucreateonaVisualBasicformbyusingatoolboxcontrol.Infact,inVisualBasic,theformitselfisalsoanobject.EveryVisualBasiccontrolconsistsofthreeimportantelements:Propertieswhichdescribetheobject,Methodscauseanobj