Professional Visual Basic® 2008 Bill Evjen Billy Hollis Bill Sheldon Kent Sharkey WileyPublishing,Inc. ® Professional Visual Basic 2008 Publishedby WileyPublishing,Inc. 10475CrosspointBoulevard Indianapolis,IN46256 www.wiley.com Copyright©2008byWileyPublishing,Inc.,Indianapolis,Indiana PublishedsimultaneouslyinCanada ISBN:978-0-470-19136-1 ManufacturedintheUnitedStatesofAmerica 10987654321 LibraryofCongressCataloging-in-PublicationData: ProfessionalVisualbasic2008/BillEvjen...[etal.]. p.cm. Includesindex. ISBN978-0-470-19136-1(paper/website) 1. MicrosoftVisualBASIC2. BASIC(Computerprogramlanguage) I.Evjen,Bill. QA76.73.B3P748762008 005.2’762--dc22 2008004975 Nopartofthispublicationmaybereproduced,storedinaretrievalsystemortransmittedinanyformorbyany means,electronic,mechanical,photocopying,recording,scanningorotherwise,exceptaspermittedunderSections 107or108ofthe1976UnitedStatesCopyrightAct,withouteitherthepriorwrittenpermissionofthePublisher,or authorizationthroughpaymentoftheappropriateper-copyfeetotheCopyrightClearanceCenter,222Rosewood Drive,Danvers,MA01923,(978)750-8400,fax(978)646-8600.RequeststothePublisherforpermissionshouldbe addressedtotheLegalDepartment,WileyPublishing,Inc.,10475CrosspointBlvd.,Indianapolis,IN46256,(317) 572-3447,fax(317)572-4355,oronlineathttp://www.wiley.com/go/permissions. LimitofLiability/DisclaimerofWarranty:Thepublisherandtheauthormakenorepresentationsorwarranties withrespecttotheaccuracyorcompletenessofthecontentsofthisworkandspecificallydisclaimallwarranties, includingwithoutlimitationwarrantiesoffitnessforaparticularpurpose.Nowarrantymaybecreatedorextended bysalesorpromotionalmaterials.Theadviceandstrategiescontainedhereinmaynotbesuitableforevery situation.Thisworkissoldwiththeunderstandingthatthepublisherisnotengagedinrenderinglegal,accounting, orotherprofessionalservices.Ifprofessionalassistanceisrequired,theservicesofacompetentprofessionalperson shouldbesought.Neitherthepublishernortheauthorshallbeliablefordamagesarisingherefrom.Thefactthatan organizationorWebsiteisreferredtointhisworkasacitationand/orapotentialsourceoffurtherinformation doesnotmeanthattheauthororthepublisherendorsestheinformationtheorganizationorWebsitemayprovide orrecommendationsitmaymake.Further,readersshouldbeawarethatInternetWebsiteslistedinthisworkmay havechangedordisappearedbetweenwhenthisworkwaswrittenandwhenitisread. ForgeneralinformationonourotherproductsandservicespleasecontactourCustomerCareDepartmentwithinthe UnitedStatesat(800)762-2974,outsidetheUnitedStatesat(317)572-3993orfax(317)572-4002. Trademarks:Wiley,theWileylogo,Wrox,theWroxlogo,WroxProgrammertoProgrammer,andrelatedtradedress aretrademarksorregisteredtrademarksofJohnWiley&Sons,Inc.and/oritsaffiliates,intheUnitedStatesand othercountries,andmaynotbeusedwithoutwrittenpermission.Allothertrademarksarethepropertyoftheir respectiveowners.WileyPublishing,Inc.,isnotassociatedwithanyproductorvendormentionedinthisbook. Wileyalsopublishesitsbooksinavarietyofelectronicformats.Somecontentthatappearsinprintmaynotbe availableinelectronicbooks. Evjen-91361 fauth.tex V1-04/01/2008 3:10pm Pagev About the Authors BillEvjenisanactiveproponentof.NETtechnologiesandcommunity-basedlearninginitiativesfor .NET.Hehasbeenactivelyinvolvedwith.NETsincethefirstbitswerereleasedin2000.Inthesameyear, BillfoundedtheSt.Louis.NETUserGroup(www.stlnet.org),oneoftheworld’sfirstsuchgroups.Bill isalsothefounderandformerexecutivedirectoroftheInternational.NETAssociation(www.ineta.org), whichrepresentsmorethan500,000membersworldwide. BasedinSt.Louis,Missouri,BillisanacclaimedauthorandspeakeronASP.NETandXMLWebServices. Hehasauthoredorco-authoredmorethan15books,includingProfessionalASP.NET3.5,Professional C#2008,ASP.NETProfessionalSecrets,XMLWebServicesforASP.NET,andWebServicesEnhancements: UnderstandingtheWSEforEnterpriseApplications(allpublishedbyWiley).Inadditiontowriting,Billisa speakeratnumerousconferences,includingDevConnections,VSLive,andTechEd.Healsoworksclosely withMicrosoftasaMicrosoftRegionalDirectorandanMVP. BillisthetechnicalarchitectforLipper(www.lipperweb.com),awhollyownedsubsidiaryofReuters,the internationalnewsandfinancialservicescompany.HegraduatedfromWesternWashingtonUniversity inBellingham,Washington,withaRussianlanguagedegree.Whenheisn’ttinkeringonthecomputer,he canusuallybefoundathissummerhouseinToivakka,[email protected]. The.NETFramework3.5releasecamequicklyforuswriters,anditwouldn’thavebeenpossibletoproducethis bookasfastaswedidifitweren’tforthededicationoftheteamsbuiltforit.TremendousthankstoKatieMohrfor beingmorethanpatientwithmeingettingthisandsomeother.NET3.5booksoutthedoor.Also,bigthanksgo outtoKevinKentfordoinghisbesttohelpingmestayonschedule. Finally,totheoneswhopaidthebiggestpriceforthiswritingsession—mywife,Tuija,andourthreekids:Sofia, Henri,andKalle—thanksforallyoudo! BillyHollisisanauthorandsoftwareconsultantbasedinNashville,Tennessee.Billywasco-authorof thefirstbookeverpublishedonVisualBasic.NET,aswellasmanyotherbooksonsoftwaredevelop- ment.HeisamemberoftheMicrosoftRegionalDirectorprogramandaMicrosoftMVP.In2002,Billy wasselectedasoneoftheoriginal.NET‘‘SoftwareLegends.’’Heisheavilyinvolvedwithconsulting, training,anddevelopmentonthe.NETplatform,focusingonarchitecture,smart-clientdevelopment, commercialpackages,anduser-interfacetechnologies.Heregularlyspeaksonsoftwaredevelopmentat majorconferencesallovertheworld,includingMicrosoft’sPDCandTechEdevents,DevConnections, VSLive,andarchitectureeventssuchasthePatternsandPracticesArchitectSummit. Iowetremendousthankstomyfamily,whohavesomehowlearnedtoputupwithmarathonwritingsessions,and tomybusinesspartner,GaryBailey,forkeepingourclientshappywhileI’mwriting. BillSheldonisasoftwarearchitectandengineer,originallyfromBaltimore,Maryland.Holdingadegree incomputersciencefromtheIllinoisInstituteofTechnology(IIT),Billhasbeenactivelyemployedasa softwareengineersinceresigninghiscommissionwiththeUnitedStatesNavy.HeisaMicrosoftMVP forVisualBasicemployedasaprincipalengineerwithInterKnowlogyinCarlsbad,California,andworks asaninstructorforVisualBasic–relatedcoursesattheUniversityofCaliforniaSanDiegoExtension. Inadditiontowritingbooks,Billhaspublisheddozensofarticles,includingtheDeveloperUpdate Newsletter,SQLServerMagazinefeaturearticles,andotherPentonpublications.Heisanestablished online presenter for MSDN and speaks at live events such as VSLive, DevConnections, Office Evjen-91361 fauth.tex V1-04/01/2008 3:10pm Pagevi About the Authors DevelopersConference,andcommunityeventssuchasusergroupsandcodecamp.Billisanavidcyclist andisactiveinthefightagainstdiabetes. Tomywonderfulwife,Tracie,whoisforcedtocarryonwhileIisolatemyselftoconcentrateonwriting.Andtothe nextgenerationofchildrenwhohavejoinedourextendedSheldonfamily(myownandmybrothers’)inthepastfive years—Nick,Elena,Ben,BillyV,Abigail,andournextson(thisspring’scomingattraction)—eachandevery oneofyouisavaluablepartofourlives. KentSharkeyisanindependentconsultantwholivesandcodesinComox,BritishColumbia.Before goingsolo,KentworkedatMicrosoftasatechnicalevangelistandcontentstrategist,promotingthe useof.NETtechnologies.Heliveswithhiswife,Margaret,andthree‘‘children’’— Squirrel,Cica, andToffee. ToBabi,forkeepingmealiveandputtingupwithme—hopefully,foralongtimetocome. vi Evjen-91361 ftech.tex V1-04/01/2008 3:11pm Pagevii About the Technical Editors MarkLavoieistheinformationsystemmanagerforamidsizedinsurancecompanylocatedinCharlotte, NorthCarolina.MarkhasworkedwithMicrosoftproductsandtechnologiesfornineyears.Hehas workedasaconsultant,managedITprojects,anddesignedandprogrammedcustomapplications.Heis anativeofCanadaand,whennotworking,enjoyscookingandvacationingwithhiswonderfulwife. ToddMeisterhasbeendevelopingusingMicrosofttechnologiesforovertenyears.He’sbeenatech- nicaleditorformorethan40titles,rangingfromSQLServertothe.NETFramework.Besidestech- nicalediting,heisanassistantdirectorforComputingServicesatBallStateUniversityinMuncie, Indiana.Hislatestdevelopmentaccomplishmentwasdevelopingane-commercesitefromscratch,which includedover15,000linesof.NETcode,creditcardintegration,giftcertificatefunctionality,anddis- countcodes.Heliveswithhiswife,Kimberly,andtheirfourchildrenincentralIndiana.ContactToddat [email protected]. AndrewMooreisagraduateofPurdueUniversity–CalumetinHammond,Indiana,andhasbeendevel- opingsoftwaresince1998forradarsystems,airtrafficmanagement,discrete-eventsimulation,and businesscommunicationsapplicationsusingC,C++,C#,andJavaontheWindows,UNIX,andLinux platforms.AndrewistheauthoroftwoWroxBloxtitles:‘‘CreateAmazingCustomUserInterfaceswith WPF,C#,andXAMLin.NET3.0’’(www.wrox.com/WileyCDA/WroxTitle/productCd-0470258713.html) and‘‘.NET3.5CDAudioPlayer.’’HeiscurrentlyworkingasasoftwareengineeratInteractiveIntelli- gence,Inc.,inIndianapolis,Indiana,developingMicrosoft-basedapplicationsforbusinesscommunica- tions.AndrewlivesinIndianawithhiswife,Barbara,andtheirtwochildren,SophiaandAndrew. Evjen-91361 fcre.tex V1-04/01/2008 3:11pm Pageix Credits AcquisitionsEditor ProductionManager KatieMohr TimTate SeniorDevelopmentEditor VicePresidentandExecutiveGroup KevinKent Publisher RichardSwadley TechnicalEditors MarkLavoie VicePresidentandExecutive ToddMeister Publisher AndrewMoore JosephB.Wikert ProductionEditor ProjectCoordinator,Cover WilliamA.Barton LynseyStanford CopyEditor Proofreaders LuannRouff EdwardMoyer,PaulSagan,WordOne EditorialManager Indexer MaryBethWakefield RobertSwanson Evjen-91361 ftoc.tex V1-04/01/2008 3:12pm Pagexi Contents Introduction xxxi Chapter 1: Visual Basic 2008 Core Elements 1 InitialKeywordsandSyntax 2 ConsoleApplications 5 ValueandReferenceTypes 8 PrimitiveTypes 10 Commands:Conditional 11 IfThen 12 ComparisonOperators 12 SelectCase 14 ValueTypes(Structures) 15 Boolean 15 IntegerTypes 16 UnsignedTypes 17 DecimalTypes 18 CharandByte 20 DateTime 21 ReferenceTypes(Classes) 21 TheObjectClass 21 TheStringClass 22 TheDBNullClassandIsDBNullFunction 25 NullableTypes 26 Arrays 27 Collections 30 Commands:LoopingStatements 32 ForEachandForNext 32 While,DoWhile,andDoUntil 33 Boxing 34 ParameterPassing 35 ParamArray 36 VariableScope 37 DataTypeConversions 38 ImplicitConversionsandCompilerOptions 39 Evjen-91361 ftoc.tex V1-04/01/2008 3:12pm Pagexii Contents XMLLiterals 42 PerformingExplicitConversions 44 Summary 47 Chapter 2: Object Syntax Introduction 49 Object-OrientedTerminology 50 Objects,Classes,andInstances 50 CompositionofanObject 50 WorkingwithObjects 54 ObjectDeclarationandInstantiation 54 ObjectReferences 55 DereferencingObjects 56 EarlyBindingversusLateBinding 56 CreatingClasses 60 BasicClasses 60 ConstructorMethods 79 TerminationandCleanup 80 AdvancedConcepts 81 OverloadingMethods 81 OverloadingConstructorMethods 84 SharedMethods,Variables,andEvents 85 OperatorOverloading 90 Delegates 93 ClassesversusComponents 98 Summary 99 Chapter 3: Object-Oriented Programming 101 Inheritance 102 ImplementingInheritance 104 PreventingInheritance 151 MultipleInterfaces 151 ObjectInterfaces 151 SecondaryInterfaces 152 Abstraction 159 Encapsulation 162 Polymorphism 165 MethodSignatures 165 ImplementingPolymorphism 165 Inheritance 176 WhentoUseInheritance 176 InheritanceandMultipleInterfaces 180 xii Evjen-91361 ftoc.tex V1-04/01/2008 3:12pm Pagexiii Contents HowDeeptoGo? 186 TheFragileBaseClassProblem 187 Summary 190 Chapter 4: The Common Language 193 Elementsofa.NETApplication 194 Modules 194 Assemblies 195 Types 196 VersioningandDeployment 197 BetterSupportforVersioning 197 BetterDeployment 198 Cross-LanguageIntegration 199 TheCommonTypeSystem 199 Metadata 200 BetterSupportforMetadata 201 Attributes 201 TheReflectionAPI 204 ILDisassembler 204 MemoryManagement 205 TraditionalGarbageCollection 206 FasterMemoryAllocationforObjects 213 GarbageCollectorOptimizations 215 Summary 217 Chapter 5: Localization 219 CulturesandRegions 219 UnderstandingCultureTypes 220 LookingatYourThread 221 DeclaringCultureGloballyinASP.NET 224 AdoptingCultureSettingsinASP.NET 225 TranslatingValuesandBehaviors 226 UnderstandingDifferencesinDates 227 UnderstandingDifferencesinNumbersandCurrencies 228 UnderstandingDifferencesinSortingStrings 231 WorkingwithASP.NETResourceFiles 233 MakingUseofLocalResources 234 MakingUseofGlobalResources 240 ResourceFilesinWindowsForms 242 Summary 246 xiii Evjen-91361 ftoc.tex V1-04/01/2008 3:12pm Pagexiv Contents Chapter 6: Generics 247 UsingGenerics 247 GenericTypes 249 GenericMethods 254 CreatingGenerics 255 GenericTypes 255 GenericMethods 264 Constraints 265 GenericsandLateBinding 268 Summary 269 Chapter 7: Namespaces 271 WhatIsaNamespace? 272 NamespacesandReferences 275 CommonNamespaces 277 ImportingandAliasingNamespaces 280 ImportingNamespaces 280 AliasingNamespaces 282 ReferencingNamespacesinASP.NET 282 CreatingYourOwnNamespaces 283 TheMyKeyword 286 My.Application 287 My.Computer 291 My.FormsNamespace 294 My.Resources 294 My.User 295 My.WebServices 295 ExtendingtheMyNamespace 295 Summary 297 Chapter 8: Exception Handling and Debugging 299 ABriefReviewofErrorHandlinginVB6 300 Exceptionsin.NET 301 ImportantPropertiesandMethodsofanException 301 HowExceptionsDifferfromtheErrObjectinVB6 302 StructuredException-HandlingKeywords 302 TheTry,Catch,andFinallyKeywords 303 TheThrowKeyword 305 ThrowingaNewException 306 xiv