Post on 09-Jun-2020
Resources
BooksAbrams, Brad. .NET Framework Standard Library Annotated Reference,Volumes 1 and 2. Boston,
MA: Addison-Wesley Professional, 2004, 2005.
Allison, Damon, Andy Olson, James Speer. Visual Basic .NET Class Design Handbook: CodingEffective Classes. Berkeley, CA: Apress, 2003.
Boehm, Anne. Murach’s Visual Basic 2005. Fresno, CA: Mike Murach & Associates, 2006.
Booch, Grady. Object-Oriented Analysis and Design with Applications, Second Edition. Boston,MA: Addison-Wesley Professional, 1993.
Box, Don, with Chris Sells. Essential .NET,Volume 1: The Common Language Runtime. Boston,MA: Addison-Wesley Professional, 2002.
Cwalina, Krzysztof, and Brad Abrams. Framework Design Guidelines: Conventions, Idioms, andPatterns for Reusable .NET Libraries. Boston, MA: Addison-Wesley Professional, 2005.
Ecma International. Standard ECMA-335: Common Language Infrastructure (CLI), Fourth Edition.Geneva, Switzerland: Ecma International, 2006.
Evjen, Bill, Rockford Lhotka, Billy Hollis, Bill Sheldon, Kent Sharkey, Tim McCarthy, RamaRamachandran. Professional VB 2005. Indianapolis, IN: Wiley Publishing, 2006.
Ferracchiati, Fabio Claudio. LINQ for VB 2005. Berkeley, CA: Apress, 2007.
Fischer, Tom, John Slater, Pete Stromquist, Chaur G. Wu. Professional Design Patterns in VB.NET: Building Adaptable Applications. Berkeley, CA: Apress, 2002.
Fowler, Martin. UML Distilled: A Brief Guide to the Standard Object Modeling Language, ThirdEdition. Boston, MA: Addison-Wesley Professional, 2003.
Freeman, Elisabeth, and Eric Freeman, with Kathy Sierra and Bert Bates. Head First DesignPatterns. Sebastopol, CA: O’Reilly Media, 2004.
Gamma, Erich, Richard Helm, Ralph Johnson, and John Vlissides. Design Patterns: Elements ofReusable Object-Oriented Software. Boston, MA: Addison-Wesley Professional, 1995.
Griver, Yair Alan, Matthew Arnheiter, Michael Gellis. Visual Basic Developer’s Guide to UML andDesign Patterns. Hoboken, NJ: Sybex, 2000.
Larman, Craig. Applying UML and Patterns: An Introduction to Object-Oriented Analysis andDesign and Iterative Development. Upper Saddle River, NJ: Prentice Hall PTR, 2004.
Lau, Yun-Tung. The Art of Objects: Object-Oriented Design and Architecture. Boston, MA:Addison-Wesley Professional, 2001.
417
A P P E N D I X A
Lhotka, Rockford. Expert VB 2005 Business Objects, Second Edition. Berkeley, CA: Apress, 2006.
Liberty, Jesse. Programming Visual Basic 2005. Sebastopol, CA: O’Reilly Media, 2005.
Moore, Karl. Karl Moore’s Visual Basic .NET: The Tutorials. Berkeley, CA: Apress, 2002.
Patrick, Tim, and John Clark Craig. Visual Basic 2005 Cookbook: Solutions for VB 2005Programmers. Sebastopol, CA: O’Reilly Media, 2006.
Richter, Jeffrey. Applied Microsoft .NET Framework Programming. Redmond, WA: MicrosoftPress, 2002.
Stephens, Rod. Visual Basic 2005 Programmer’s Reference. Indianapolis, IN: Wiley Publishing, 2005.
Stoecker, Matthew, with Microsoft Corporation. MCAD/MCSD Self-Paced Training Kit:Developing Windows-Based Applications with Microsoft Visual Basic .NET and Visual C#.NET, Second Edition. Redmond, CA: Microsoft Press, 2003.
Sutter, Herb. Exceptional C++: 47 Engineering Puzzles, Programming Problems, and Exception-Safety Solutions. Boston, MA: Addison-Wesley Professional, 1999.
Troelsen, Andrew. Pro VB 2005 and the .NET 2.0 Platform. Berkeley, CA: Apress, 2006.
Yourdon, Edward, and Larry L. Constantine. Structured Design: Fundamentals of a Discipline ofComputer Program and Systems Design. Upper Saddle River, NJ: Prentice Hall, 1979.
ArticlesKaplan, Michael, and Cathy Wissink. “Custom Cultures: Extend Your Code’s Global Reach With
New Features In The .NET Framework 2.0.” MSDN Magazine, October 2005.
Robbins, John. “Unhandled Exceptions and Tracing in the .NET Framework 2.0.” MSDNMagazine, July 2005.
Schmidt, Douglas C. “Monitor Object: An Object Behavioral Pattern for ConcurrentProgramming.” Department of Computer Science and Engineering, WashingtonUniversity, St. Louis, MO, April 2005.
Toub, Stephen. “High Availability: Keep Your Code Running with the Reliability Features of the.NET Framework.” MSDN Magazine, October 2005.
Vermeulen, Allan. “An Asynchronous Design Pattern.” Dr. Dobb’s Journal, June 1996.
Ng, Timothy. “Basic Instincts: Lambda Expressions.” MSDN Magazine, September, 2007.
Horst, Bill. “Basic Instincts: Type Inference in Visual Basic 2008.” MSDN Magazine, October2007.
Web101 LINQ Samples. http://msdn2.microsoft.com/en-us/vbasic/bb688088.aspx
101 Samples for Visual Basic 2005. http://msdn2.microsoft.com/en-us/vbasic/ms789075.aspx
The Code Project. www.codeproject.com/
Developer.com. www.developer.com/net/vb/
Free Book - Introducing Microsoft Visual Basic 2005 for Developers.http://msdn2.microsoft.com/en-us/vbrun/ms788235.aspx
APPENDIX A ■ RESOURCES418
Visual Basic 2008 Express Edition. http://msdn2.microsoft.com/en-us/express/future/bb421469.aspx
VB.Net Heaven. www.vbdotnetheaven.com/
Visual Basic Developer Center. http://msdn2.microsoft.com/en-us/vbasic/default.aspx
Consuming Unmanaged DLL Functions. http://msdn2.microsoft.com/en-us/library/26thfadc(vs.90).aspx
A Closer Look at Platform Invoke. http://msdn2.microsoft.com/en-us/library/0h9e9t7d(vs.90).aspx
Code Access Security: When Role-Based Security Isn’t Enough. http://www.devx.com/security/Article/31259/0/page/1
How to Create an Indexer Property in Visual Basic .NET or in Visual Basic 2005.http://support.microsoft.com/kb/311323
How to Demand Permissions by Using Code Access Security.http://support.microsoft.com/kb/315529
Code Access Security. http://msdn2.microsoft.com/en-us/library/930b76w0(VS.90).aspx
Code Access Permissions. http://msdn2.microsoft.com/en-us/library/h846e9b3(vs.90).aspx
Unicode Frequently Asked Questions. http://unicode.org/faq/utf_bom.html
Wikipedia, “Regular Expression,” http://en.wikipedia.org/wiki/Regular_expression, 2007.
Regular Expression Tutorial. http://www.regular-expressions.info/tutorial.html
Array Covariance Rules. http://msdn2.microsoft.com/en-us/library/aa664572(VS.71).aspx
The LINQ Project. http://msdn2.microsoft.com/en-us/netframework/aa904594.aspx
Hooked on LINQ. http://www.hookedonlinq.com/MainPage.ashx
Beth Massi, “Sharing the Goodness that is VB: Quickly Import and Export Excel Data with LINQto XML,” http://blogs.msdn.com/bethmassi/archive/2007/10/30/quickly-import-and-export-excel-data-with-linq-to-xml.aspx
Douglas Reichard, “Shim Classes,” http://www.ddj.com/cpp/184401200?pgno=5
Deployment of Managed COM Add-Ins in Office XP. http://msdn2.microsoft.com/en-us/library/aa164016(office.10).aspx
APPENDIX A ■ RESOURCES 419
Running the Examples
This appendix describes the various types of code examples throughout the book and how torun them. It is meant to aid you if you’re new to the VB 2008 environment.
Example TypesThis book contains three types of code examples: code snippets; classes, structures, and inter-faces and console applications.
Code SnippetsA code snippet is a short code sample used to display the syntax of an entire method or singlefunction call. These samples are not meant to be compiled or executed.
Classes, Structures, and InterfacesThese examples contain class, structure, and interface definitions. You build these by usingthe Class Library project type. Chapter 6 contains several examples that fall into this category.
Console ApplicationsThese examples, built using the Console Application project type, are the most prevalent typeof code example in the book. By default, VB creates a Module1.vb file with the following stub:
Module Module1Sub Main()End Sub
End Module
We recommend that you replace the entire Module stub with the example text, which con-tains a Public EntryPoint class and a Shared Main method. Next, in your project’s Propertiespage, on the Application tab, set the “Startup object:” to “Sub Main.” For examples that requirecommand-line arguments, you can enter these, separated by spaces, in your project’s Propertiespage, on the Debug tab, in the “Command line arguments” input area. Finally, the few samplesthat discuss globalization require a message box to display the results. You should build andrun these examples the same way as other console applications, but you need to add a refer-ence to System.Windows.Forms in your project’s Properties page, on the References tab.
421
A P P E N D I X B
Running a Console Application via the Debug ➤ Start Without Debugging menu, or theCtrl+F5 shortcut, will launch the application, displaying each output as needed, then pausewith a “Press any key to continue . . .” message when execution is complete.
For a more thorough understanding of an example, place a breakpoint on the first exe-cutable line inside Shared Sub Main(), and “Step Into” or “Step Over” each line of code whilereviewing the call stack, any variables, and console output.
A Few Words Regarding ModulesIf you’re an experienced object-oriented developer, the concept of a module may seem foreign.The Module construct, which cannot be instantiated, is a feature carried over from Visual Basic6.0 (VB6) to facilitate migration of those applications to .NET.
A Module, when compiled, is converted to a NotInheritable class with Shared members.These Shared members are available to your entire application, acting like a global variable.This may not be what you desire. Classes, on the other hand, are not automatically Shared.
We consider creating an EntryPoint class, containing a Shared Sub Main method, to bethe much better practice for creating object-oriented systems with VB.
APPENDIX B ■ RUNNING THE EXAMPLES422
■AA(Of T), 241Abort(), 277-279aborting threads, 277access modifiers, 36-38accessors, 78AcquireReaderLock(), 302AcquireWriterLock(), 302Activator class, 270Add() method, 74, 244, 246Add(Of Integer), 246Add(Of T) method, 246AddHandler statement, 232-233addition (+) operator
composite strings, 184overloading, 121-122
AddressOf operator, 220aliases, assigning to namespaces, 28allocated resources, exceptions, 158-161AllocateDataSlot(), 283, 285AllocateNamedDataSlot method, 283anonymous types, 9, 375-376APIs
LINQ to Objects, 8LINQ to XML, 7
AppDomain.IsFinalizingForUnload, 340AppDomain.UnhandledException, 136AppDomainUnloadException, 136Append() method, 184AppendFormat() method, 184application domains
finding with LINQ, 385-386shared fields and, 81
ApplicationException, 157ApplyRaiseOf method, 224, 226ArgumentException, 205ArgumentOutOfRange exception, 135-136
exception-neutral code and, 145shared constructors and, 141
ArgumentOutOfRangeException, 184array initializers, 7Array.GetLength(), 201ArrayList, boxing, 239arrays, 197-200
covariance, 199, 238declaring, 197-198
jagged arrays, 202-203multidimensional, 200-201
generics, 238multidimensional, 200-203
declaring, 200-201jagged, 202-203mapping to mathematical concepts,
202ParamArray, 73-74range checking, 198ranks, 199
multidimensional arrays, 202RankException, 200
searchability, 200sortability, 200synchronization, 200type convertibility, 198-199
As keyword, 254assemblies, 88-91
cross-language compatibility, 95culture-neutral, 93-94global assembly cache (GAC), 92-94header information, 88-89loading (probing), 94-95managed assemblies, 91management of, 91-92metadata, 95private, 92shared, 92-94versioning, 95viewing manifests, 89-90, 92viewing metadata, 90-91
assembly language, IL (intermediatelanguage), 86-87
asynchronous exceptions, 148, 150asynchronous method calls, 311-315asynchronous processing, IOU pattern,
310, 312AutoResetEvent, 306-307
■Bbackground threads, 280-281
IsBackground property, 315Base Class Library (BCL), 3base class version of methods, calling, 76BeginInvoke(), 311-315BeginInvoke()/EndInvoke() pattern, 315BeginMethod()/EndMethod() pattern, 310BeginProcessData()/EndProcessData()
pattern, 310
423
Index
best practices. See reference-type bestpractices; value-type best practices
binary operators, overloading, 117-118BinarySearch(), 200Boolean operators, overloading, 126-129boxing, 22-23, 52-57
efficiency of, 56-57generics, 239instances of, 55-56synchronizing threads, 295-296value types, 368
Bridge pattern, 230browsing namespaces with Object Browser,
28ByRef arguments, 71-73ByVal arguments, 71
■CC# .NET runtime, 1-2C# 3.0 versus VB 2008, 2-3callbacks
delegates. See delegatesevents. See events
CallDelegates method, 247calling base class version of methods, 76canonical forms
reference-type best practices, 317checklist, 361-362cloneable objects, 320-322, 324-326defaulting to NotInheritable classes,
317-318disposable objects, 334-336finalizers, 337-341, 343-344formattable objects, 326-331immutable reference types, 358, 360NVI pattern, using, 318-320object equality, 344-350ordering objects, 331-332, 334overriding GetHashCode(), 350-353type safety, 353-354, 356-357
value-type best practices, 362-372checklist, 371-372implementing type-safe forms, 368, 371overriding Equals(), 363, 365, 367
carriage return/line feed (CRLF), linetermination, 29
casting reference types, DirectCast andTryCast, 22
Catch blocks, 134-138CERs (constrained execution regions),
148-150, 154chaining delegates, 220-222
iterating through delegate chains, 222-224chaining operations on string builder, 184ChangeType(), 330
checklistsreference types, 361-362value-types, 371-372
class constraints, 254class definition, 35-36
accessibility/access modifiers, 37-38constructors, 36interfaces, 38-39item property indexers, 46, 48MustInherit classes, 42-43MyBase and MyClass keywords, 39-42nested classes, 43, 45-46NotInheritable classes, 42partial classes, 48
Class keyword, 17, 35Class Library project type, 421classes
Activator, 270Array, 238Base Class Library (BCL), 3best practices. See reference-type best
practicesComparer(Of T), 266Convert, 20, 329-330Coordinate, 20-21creating custom exception classes, 155-158CultureAndRegionInfoBuilder, 171-172definitions. See class definitionDimensions, 325EntryPoint, 422EventArgs, 231EventHandler(Of T), 231generic, 241-242generic. See generics, 237GraphCoordinate, 20-21implementing contracts, 107-109
vs. interfaces, 110-113implementing multiple interfaces, 101-102inheritance, 39-42
MustInherit classes, 42-43NotInheritable classes, 42
Interlocked, 148methods of, 285synchronization, 286-290
Iterator, 45LINQ to SQL database/field mapping,
408-411Monitor, 285
versus Mutex, 291Monitor, synchronizing threads, 291-295
boxing, 295-296Pulse() and Wait(), 296-300
MulticastDelegate, 217-218MustInherit, 42-43
■INDEX424
Mutex, 285lock objects, 305-306transition to kernel mode, 286versus Monitor, 291
nested, 43, 45-46non-nested, 43, 45NotInheritable, 42
defaulting to, 317-318overriding methods in derived classes,
75-77partial, 48PlayerUI, 232-233PlayEventArgs, 231QueueProcessor, 274ReaderWriterLock, 301-303ReaderWriterLockSlim, 303-305Regex, 186RuntimeHelpers, 148SafeHandle derived classes, 150-154sealed, NotInheritable methods, 77SpinLock, 290StringBuilder, 184-185StringComparer, 180System.Attribute, 95System.Char, 167System.Delegate, 220System.Exception
constructors, 155, 157-158exception handling, 135inner exceptions, 138, 141
System.Monitor, 200System.Object, 12System.Reflection, 95System.String, 167System.Text.Encoding, 168, 181-183System.Thread, 273Threading.Interlocked, 286ThreadPool. See thread poolWaitHandle, 306-309
WaitOne(), 306-307cleaning up directly held resources, 337CLI (Common Language Infrastructure),
85, 167Clone() method, 167. See also ICloneable
custom attributes, 324-325cloneable objects, reference-type best
practices, 320-326Close() method, 159-160closed types, 240-241code snippets, 421console applications, 421-422CLR (common language runtime), 1-2, 85
assemblies, 88-91cross-language compatibility, 95global assembly cache (GAC), 92-94loading (probing), 94-95managed assemblies, 91
management of, 91-92private, 92shared, 92-94versioning, 95viewing manifests, 89-92viewing metadata, 90-91
callback mechanism. See delegatesCommon Language Infrastructure (CLI)
standard, 85, 167common type system, 3-5entry-point methods, 91-92exception handling, 133. See also
exception handlingcritical finalizers, 150finalizers, 140-141lack of deterministic destruction, 158SafeHandle, 150-151, 153-154
exception-neutral codeasynchronous exceptions, 148, 150CERs (constrained execution regions),
148-150operations, 147
garbage collection, 3IL (intermediate language)
JIT compiling, 87-88VB compiler and, 85-87
impact on VB language, 3internal string representation format, 183managed code, 1metadata, 95performing optimizations at run time, 87-
88JIT compiling, 87-88
CLS (Common Language Specification), 14code
assemblies. See assembliesexception-neutral code, 143exception-safe coding, 133managed code, 1writing exception-neutral
constrained execution regions (CERs),148-150
critical finalizers and SafeHandle, 150-154
rollback behavior, 162-165structure of, 143-148
Collection(Of T), 208-209, 242collections, 203-211
defining collection types, 208-211dictionaries, 208generic, 255-257ICollection, 203-205lists, 206-207synchronization, 205-206System.Collection.ObjectModel, 208-211types that produce collections, 206
colon (:), multiple statements, 29
■INDEX 425
Combine() method, 220, 222, 233Commit() method, 162, 164Common Language Infrastructure (CLI)
standard, 85, 167common language runtime. See CLR
(common language runtime)Common Language Specification (CLS), 14common type system (CTS), 3-5CompareExchange(), 288, 290Comparer(Of T) class, 266CompareTo(), 331-332, 368, 371comparing strings, 180-181comparison operators, overloading, 122, 125-
129compiler, method overloading and, 74CompilerServices namespace, 148complex numbers, references to, 347composite strings, 184Console.WriteLine(), 174-175, 177Const fields, 82constants, enumerations, 16-17constrained execution regions (CERs),
148-150, 154constraints
class, 254generics, 251, 253-255IConvertible, 266New, 254primary, 254structure, 254
constructed types, generics, 240accessibility, 251creating dynamically, 268-270
constructed types. See closed typesconstructors, 36, 49-50
CorePlayer, 232instance, 61-62Shared, 60-61, 141-142System.Exception class, 155-158
Container identifier, 241container types, generic delegates, 245Container(Of T), 241Contains queries (LINQ to Objects), 384Continue, 33contracts, 97, 107, 253
classes, 107-109classes vs. interfaces, 110-113interfaces, 109-110
control flow constructsIf . . . Then . . . Else, 29-30Select . . . Case, 30
controlling execution flow, exceptionhandling, 134
conversion operators, overloading, 117-119,129-130
CType, 130-131conversions, boxing and, 55
Convert class, 20, 329ChangeType(), 330
ConvertAll(Of TOutput)() method, 249Converter(Of T, Of R) delegate, 244Converter(TInput, TOutput) delegate, 245convertible objects, best practices, 329-331converting floating-point values to strings,
171converting types, 19-20
boxing conversions, 22-23Convert class, 20CType, 20-21DirectCast and TryCast, 22explicit conversion, 19-20generics, 248-249, 257-268reference type operators, 23-25widening conversions, 13, 19
Coordinate class, 20-21Copy() method, 167copying objects, cloneable objects best
practices, 320-326CopyTo(), 205CorePlayer constructor, 232Count queries (LINQ to Objects), 381-382covariance, arrays, 199CreateClosedType(Of T)() method, 269CreateInstance(), 270critical finalizers, 148, 150-154CriticalFinalizerObject, 150CRLF (carriage return/line feed), line
termination, 29cross-language compatibility of assemblies,
95CRUD (Create, Read, Update, and Delete),
LINQ to SQLCreate, 411-412Delete, 414-415Read, 413Update, 413-414
CTS (common type system), 3-5CType, 20-21
overloading, 117-119, 130-131culture-neutral assemblies, 93-94CultureAndRegionInfoBuilder, 171-172CultureInfo, 169-172, 327
comparing strings, 180-181custom CultureInfo types, 171-172format strings, 173-174
CurrencyDecimalDigits property, 174CurrencyDecimalSeparator property, 174CurrencySymbol property, 174custom events, 232-233custom exception classes, creating, 155-158custom formatter (ICustomFormatter),
177, 180custom types, string formatting, 175-177
■INDEX426
■Ddata context (LINQ to SQL), 411data types. See typesdatabases, LINQ to SQL. See LINQ to SQLDateTimeFormatInfo, 170, 174DBG, 173, 177declarative mapping, 100declaring. See also defining
arrays, 197-198jagged arrays, 202-203multidimensional, 200-201
delegates, 218-220generic types, 237-238, 240-241interfaces, 98-100, 102-103properties, 78-80string literals, 168-169
Decrement(), Interlocked class, 286deep copies, 320-321default constructors, 36default field values, 84deferred evaluation, LINQ queries, 386-387defining
classes. See class definitionscollection types, 208-211contracts, 107generics, 237-238interfaces, 98-100, 102-103namespaces, 26-27value types. See value type definitions
Delegate keyword, 218Delegate.Combine() method, 233Delegate.Remove() method, 233delegates, 217
chaining, 220-222creating, 218-220events. See eventsgeneric, 244-248iterating through delegate chains, 222-224open-instance, 224-227relaxed, 233-235removing from delegate lists, 220Strategy pattern, 228-229
deleting table records (LINQ to SQL), 414-415deploying
private assemblies, 92shared assemblies, 94
derived classesEventArgs, 231overriding methods in, 75-77
design checklists for value types, 372design patterns
Non-Virtual Interface (NVI), 109Singleton, 109, 242
destroying objectsexception handling, 63finalizers, 62-63
destructor, 337deterministic destruction, 158-161deterministic finalization, 65dictionaries, 208Dimensions class, 325DirectCast, 22directly held resources, cleaning up, 337disassembler (IL DASM), 85-86, 88
boxing and, 56-57viewing
assembly header information, 88-89assembly manifests, 89-90, 92assembly metadata, 90-91
disposable objects, 63-67best practices, 334-336IDisposable interface, 63-65Using keyword, 65-67
Disposable pattern, 336Dispose() method, 63, 65, 158, 160, 162, 164,
215. See also IDisposablefinalization and, 340Using keyword, 65, 67
Distinct queries (LINQ), 374LINQ to XML, 401
DLLsassemblies. See assembliesDLL Hell, 95
Do Until, 32-33Do While, 32-33DoSomeWork method, 229DowngradeFromWriterLock(), 302
■Eearly binding, 3Ecma International, 85efficiency, generics, 238-240embedded expressions, LINQ to XML, 389Employee.ApplyRaiseOf method, 224encapsulation. See propertiesenclosing type, 119encoding, strings and, 181-183EncodingGetByteCount() method, 183EndInvoke(), 311-315EndProcessData(), 274Enter()
Monitor class, 291-296SpinLock class, 290
EntryPoint class, 422entry-point methods, 91-92enumerations, 16-17enumerators, creating, 211-215Environment.HasShutdownStarted, 340equality, 344
identity equality, 344-347overriding GetHashCode(), 350-353overriding Object.Equals(), 347-350
equality operators, 350
■INDEX 427
Equals(), 344, 350-353identity equality, 344-347Object keyword, 58overriding, 347-350, 363-367overriding Object.Equals(), 347-350
Event keyword, 231EventArgs derived class, 231EventHandler(Of T) class, 231events, 229-232
custom, 232-233end, 229, 235raising, 232relaxed delegates, 233-235synchronizing threads, 306-307
EventWaitHandle, transition to kernel mode,286
Excel spreadsheets, creating with LINQ, 403-405
Exception Assistant, 142NullReferenceException was unhandled
dialog, 141TypeInitializationException was
unhandled dialog, 142exception handling, 133-134
destroying objects, 63exception naming conventions and, 155Expert pattern, 133flow control and, 134inner exceptions, 138-142throwing exceptions, 136
exceptions thrown in finalizers, 140-141exceptions thrown in Finally blocks,
139-140exceptions thrown in shared
constructors, 141-142rethrowing, 137-139Throw statements, 136Try statement, 134-136
translating exceptions, 137-139unhandled exceptions in .NET 3.5, 136
exception-neutral code, 143constrained execution regions (CERs),
148-150critical finalizers and SafeHandle, 150-154rollback behavior, 162-165structure of, 143-148
Exception.InnerException property, 138-141exceptions
allocated resources, 158-161ArgumentOutOfRange, 135-136asynchronous, 148, 150custom exception classes, creating,
155-158exception-neutral code. See exception-
neutral codehandling. See exception handlingInvalidCastException, 239-240
InvalidOperationException, 200, 204KeyNotFoundException, 208NotSupportedException, 211NullReferenceException, 136ObjectDisposedException, 335RankException, 200rollback behavior, 162-165SynchronizationLockException
exceptions, 296system-generated exceptions, 136ThreadAbortException, 277-279ThreadInterruptedException, 279unhandled exceptions in .NET 3.5, 136
Exchange(), 288, 290EXE files. See assembliesExit For, 32Exit(), 291-296Expert pattern, 133explicit aliases, assigning to namespaces, 28explicit type conversion, 19-20extension methods, 9, 376-377
Contains, 384creating, 377Min, Max, and Count, 381-382
■Ffields, 80-84
Const, 82default value, 84initialization, 82-84instance fields, 80read only, 79-82shared, 80-81
Finalize(), 3destroying objects, 62-63Object keyword, 58
finalizers, 51, 62-63, 337best practices, 337-344critical, 148-154exceptions thrown in, 140-141versus destructors, 337
Finally blocksexception handling, 135-136, 159-161
exceptions thrown in Finally blocks,139-140
rethrowing exceptions, 137Try blocks, 134
rollback behavior, 164-165ThreadAbortException, 277
finding documents with LINQ, 385-386Finished state, threads, 275floating-point values, converting to strings, 171flow control
exception handling and, 134If . . . Then . . . Else, 29-30Select . . . Case, 30
For . . . Next, 32
■INDEX428
For Each . . . Next, 31-32For Each statement, 211-215
array iteration, 198collections, 206jagged arrays, 203multidimensional arrays, 201multidimensional jagged arrays, 202-203type safety and, 354-357
For loops, array iteration, 201-202foreground threads, 280-281format providers, 170-171format specifiers, strings, 169
comparing strings, 180-181Console.WriteLine(), 174-175CultureInfo, 169-172custom types, 175, 177format strings, 173-174ICustomFormatter, 177, 180IFormattable, 169-171Object.ToString(), 169-171String.Format(), 174-175
formattable objects, best practices, 326-329formatting strings. See format specifiers,
stringsFriend, 37Friend to Structure, 37From queries (LINQ), 374
LINQ to XML, 399-400From queries (LINQ to Objects), 379fully (strongly) named assemblies, 91Func type (LINQ), 378function pointers. See delegatesfunctions
CType, 20-21explicit type conversion, 19-20inline (LINQ), 378-379PrintCoordinates, 20-21
■GGAC (global assembly cache), 92-94gacutil.exe, 94garbage collector (GC), 3, 17, 62
finalizer performance impact on, 340-341reference types, 17-18
GC. See garbage collectorGC.SuppressFinalize(), 340GenerateNumbers(), 211generic comparer, 256generics, 237-238
closed types, 240-241constraints, 251-255efficiency, 238-240interfaces
using generic interfaces, 105-106using generic methods in interfaces,
106-107NonGeneric method, 240
open types, 240-241operators, 257-259, 261-268overloaded types, 241, 244system collections, 255-257type declaration, 237-238
open and closed types, 240-241type definitions and constructed types, 240
accessibility, 251classes and structures, 241-242creating constructed types dynamically,
268-270delegates, 244-248interfaces, 242methods, 243-245nullable types, 249-250type conversion, 248-249, 257-268
type parameters, 237type placeholder naming conventions, 240type safety, 238-240
genre data (LINQ to XML), 389-392adding elements to documents, 390-391creating documents, 389-390saving documents, 392
Get accessors, 78Get(), multidimensional arrays, 202GetEnumerator(), 212, 215GetFormat(), 177, 327-329GetHashCode(), 273
Object keyword, 58overriding, 350-353
GetInvocationList method, 222, 224GetLength(), 202GetLowerBound(), 202GetMinThreads(), 310GetNamedDataSlot(), 285GetString() method, 183GetType method, Object keyword, 57GetUpperBound(), 202global assembly cache (GAC), 92-94globalization, strings, 169
comparing strings, 180-181Console.WriteLine(), 174-175CultureInfo, 169-172format strings, 173-174ICustomFormatter, 177, 180IFormattable, 169-171Object.ToString(), 169-171string formatting in custom types, 175-177String.Format(), 174-175
GraphCoordinate class, 20-21grouping and searching strings, 187-191
■Hhalting threads, 279-280Handle property, 309handling exceptions. See exception handlingheader information in assemblies, 88-89
■INDEX 429
Hello World! program, 5hiding interface members, 102-103
■IIAsyncResult interface, 313ICloneable, 58, 167
reference types, 320-321value types, 362
ICollectionsynchronization
arrays, 200collections, 205
versus ICollection(Of T), 203-205ICollection(Of T), 208IComparable, 122, 125-126, 256
arrays, 200CompareTo(), 331-332, 368, 371System.Int32 and, 105
IComparer, 180, 256, 266IConvertible, 266
System.Int32 and, 105ToType(), 330
identity equality, 344-347IDictionary (Of TKey, TValue) interface, 208IDisposable, 63-65, 158, 162, 215, 334
destructor code and, 337Disposable pattern and, 336implementing, 335value types, 362WaitHandle type, 309
IEnumerablecollection types, 203iteration, 211-215System.Array, 198
IEnumerable(Of T), 242defining collection types, 209-210iteration, 211-215collection types, 203
IEnumeratoriteration, 211-215type safety and, 354, 356
IEnumerator(Of T)defining collection types, 209-210iteration, 211-215
IEquatable(Of T), 350, 365If . . . Then . . . Else, 29-30IFormatProvider, 170-171
GetFormat(), 177replacement strings and, 175
IFormattable, 169-171, 175, 177, 327System.Int32 and, 105ToString method, 175ToString(), 328
IL (intermediate language), 1-2as assembly language, 86-87JIT compiling, 87-88VB compiler and, 85-87
IL Disassembler (IL DASM), 85-86, 88boxing and, 56-57viewing
assembly header information, 88-89assembly manifests, 89-90, 92assembly metadata, 90-91
IList interface, 200, 206-207IList(Of T) interface, 206-207, 239immediate evaluation, LINQ queries, 388-389immutable reference types, 358-360implementing
contractsclasses, 107-109classes vs. interfaces, 110-113interfaces, 109-110
ICloneable interface, 321IDisposable interface, 335interfaces
in structures, 103-105multiple interfaces, 101-102reference types, 97-98value types, 105
Implements, 39, 100IMPLEMENTS relationships, modeling, 113implicitly typed local variables, 6Imports statement, 27Increment(), 286Index(), 200indexers, 46-48IndexOf() method, 185IndexOutOfRangeException, 198inheritance, 39-42
interfaces, 101MustInherit classes, 42-43NotInheritable classes, 42overridden methods, 77
initialization of fields, 82-84initializer expressions, 61inline functions (LINQ), 8, 378-379inner exceptions, 138-142Insert() method, 184instance constructors, 36, 61-62instance fields, 80instance methods, 70-71IntelliSense, 9interfaces, 38-39, 51, 97
Class Library project type and, 421components of, 100contracts, 253DateTimeFormatInfo, 170, 174defining, 98-100
hiding members, 102-103generic, 242
using generic interfaces, 105-106using generic methods in interfaces,
106-107IAsyncResult, 313
■INDEX430
ICloneable, 58, 167, 362reference types, 320-321
ICollectionsynchronization, 200, 205versus ICollection(Of T), 203-205
IComparable, 122, 125-126, 256arrays, 200CompareTo(), 331-332, 368, 371System.Int32 and, 105
IComparer, 256, 266IConvertible
System.Int32 and, 105ToType(), 330
ICustomFormatter, 177, 180IDictionary (Of TKey, TValue), 208IDisposable, 63-65, 158, 162, 215, 334
destructor code and, 337Disposable pattern and, 336implementing, 335value types, 362
IEnumerablecollection types, 203iteration, 211-215System.Array, 198
IEnumerable(Of T), 242collection types, 203defining collection types, 209-210iteration, 211-215
IEnumeratoriteration, 211-215type safety and, 354-356
IEnumerator(Of T)defining collection types, 209-210iteration, 211-215
IEquatable(Of T), 350, 365IFormatProvider, 170-171
GetFormat(), 177replacement strings and, 175
IFormattable, 175, 177, 327System.Int32 and, 105ToString method, 175, 328
IList, 200, 206-207IList(Of T), 206-207, 239implementing
contracts, 109-113multiple interfaces, 101-102reference types, 97-98Strategy pattern, 228in structures, 103-105value types, 105
inheritance, 101IShape, 253methods and, 100NumberFormatInfo, 170-171, 174polymorphism, 114-115type-safe forms of interface members,
368, 371
Interlocked class, 148methods of, 285synchronization, 286-290
intermediate language (IL), 1-2as assembly language, 86-87JIT compiling, 87-88VB compiler and, 85-87
intern pool, 168Interrupt(), 275, 279IntToLongConverter method, 244, 246InvalidCastException, 239-240, 330InvalidOperationException, 200, 204invocation lists, 217
GetInvocationList method, 222, 224removing delegates, 220
Invoke method, 311IOException, 159IOU pattern, 310, 312Is operator
IsNot and, 25TypeOf keyword and, 23-24
is-a relationships, modeling, 113IsBackground property, 315IShape interface, 253IsInvalid property, 154IsNot operator, 25ISomeInterface, 238-239IsReadOnly property, 204iteration, 211-215
Continue, 33Do While and Do Until, 32-33For . . . Next, 32For Each . . . Next, 31-32For Each statement, 211-215modifying or passing iterator variables to
methods, 31multidimensional arrays, 201-202multidimensional jagged arrays, 202-203through delegate chains, 222-224
Iterator class, 45
■Jjagged arrays (multidimensional), 202-203JIT (just-in-time) compiler, 1-2, 87-88Join(), 275, 280
LINQ, 375, 402-403
■Kkernel
kernel mode objects, 306transitions to kernel mode, avoiding via
Threading.Interlocked class, 286KeyNotFoundException, 208keywords
As, 254ByRef, 72Class, 17, 35
■INDEX 431
Const, 82Delegate, 218DirectCast, 22Event, 231Implements, 39Me, 50-51
instance methods and, 71locking objects, 294-295unboxing, 57
MustInherit, 42-43MyBase, 39-40MyClass, 40-42Narrowing, 131New, 58-59, 245NotInheritable, 42Object, 12, 57-58Of, 237ParamArray, 73Partial, 48Structure, 15, 35SyncLock, 200, 205-206, 293, 296TryCast, 22TypeOf, 21, 23-24Using, 65, 67, 336
exception handling and, 161-162value, 233Widening, 131
■LLambda expressions, 8, 378-379
Count, 382Language-Integrated Query. See LINQLastIndexOf() method, 185, 200LastIndexOfAny() method, 185late binding, 2-3LDML (Locale Data Markup Language) file,
171Let queries (LINQ to Objects), 383line termination, 29LINQ (Language-Integrated Query), 373-379
extension methods, 376-377Contains, 384creating, 377Min, Max, and Count, 381-382
Lambda expressions, 378-379Count, 382
query comprehensions, 373-374syntax, 374-375type inference, 375-376
LINQ to Objects, 8, 379-389finding documents, 385-386queries, 379-385
Contains, 384From, 379Let, 383Min, Max, and Count, 381-382
Order By, 380-381subqueries, 384-385Where, 380
query evaluation, 386-389LINQ to SQL, 405-416
Create, Read, Update, and Delete (CRUD)Create, 411-412Delete, 414-415Read, 413Update, 413-414
creating databases/tables, 406-408data context, 411database operations, 411-416
adding data to tables, 411-412deleting table records, 414-415reading tables, 413reviewing generated SQL, 415-416updating table records, 413-414
mapping tables to mapping/entity classesGenre class, 408-409Musician class, 410-411
LINQ to XML, 7, 389-405creating Excel spreadsheets, 403-405genre data, 389-392
adding elements to documents, 390-391creating documents, 389-390saving documents, 392
musician data, 393adding elements to documents, 394-395adding elements to specific locations,
395-397creating documents, 393saving documents, 398-399
queries, 399-403Distinct, 401From, 399-400Join, 402-403Select, 400-401Where, 401-402
List(Of T), 242lists, 206-207ListSwap() method, 147-148, 150loading assemblies (probing), 94-95Locale Data Markup Language (LDML) file,
171locks. See also synchronizing threads
locking objects, 300-306Mutex, 305-306ReaderWriterLock, 301-303ReaderWriterLockSlim, 303-305
Me keyword, 294-295spin locks, 288-290SpinLockManager, 290, 293SynchronizationLockException
exceptions, 296SyncLock keyword, 293, 296
■INDEX432
loopingContinue, 33Do While and Do Until, 32-33For . . . Next, 32For Each . . . Next, 31-32
■MMain() method, 5, 71, 244-245MakeGenericType(), 269-270managed applications, 85managed assemblies, 91managed code, 1managed threads, 271, 275-277manifests, assemblies, 89-90, 92ManualResetEvent, 306-307mapping multidimensional arrays to
mathematical concepts, 202Match() method, 187, 194MatchEvaluator delegate, 192-193Max queries (LINQ to Objects), 381-382Me, 50-51
instance methods and, 71locking objects, 294-295unboxing, 57
Me.New(), 36-37MemberwiseClone(), 321
Object keyword, 57metadata, 95
assemblies, 90-91reflection, 95
method overloading, 74methods, 69. See also specific methods
Add, parameter arrays, 74base class version of, calling, 76Clone, 324-325Console.WriteLine(), 177Dispose(), 63-65
Using keyword, 65-67EncodingGetByteCount(), 183extension methods, 9, 376-377
Contains, 384creating, 377Min, Max, and Count, 381-382
field initialization, 84Finalize(), 62-63generic, 243-245
using in interfaces, 106-107GetString(), 183instance, 70-71interfaces and, 100Main, 71MustOverride, 74-77naming, 98NonGeneric, 240Object keyword, 57-58overloading, 74
Overridable, 74-77cautions when using, 77NotInheritable classes, 317NotInheritable modifier, 77Overrides and Shadows modifiers, 75-77
parameters, 71-74ByRef arguments, 71-73ByVal arguments, 71ParamArray keyword, 73-74
PassByRef, 72-73PassByValue, 72Public Shared Operator, 118shared, 69-70SomeFunction, 70SomeOperation, 71String.Compare(), 180String.Intern(), 169StringComparer.Create(), 181ToString(), 169-170type-safe forms of derive methods, 368,
371versus indexers, 46
Microsoft Intermediate Language (MSIL)Assembler, 2
Min queries (LINQ to Objects), 381-382mirror overloads, 120modifying iterator variables, 31Module construct, 422Module1.vb file, 421modules, 95, 422Monitor class, 285
synchronizing threads, 291-295boxing, 295-296Pulse() and Wait(), 296-300
versus Mutex, 291Wait(), 275
MoveNext(), 215MulticastDelegate class, 217-218multidimensional arrays, 200-203
declaring, 200-201jagged, 202-203mapping to mathematical concepts, 202
multithreading. See threadingmusician data (LINQ to XML), 393
adding elements to documents, 394-395adding elements to specific locations, 395-
397creating documents, 393saving documents, 398-399
MustInherit classes, 42-43MustOverride method, 74-77mutating operands, 119Mutex class, 285
lock objects, 305-306transition to kernel mode, 286versus Monitor, 291
■INDEX 433
My namespace, 5My.Application.UnhandledException, 136MyBase identifier, 76MyBase keyword, 39-40MyBase.New(), 36-37MyClass keyword, 40-42MyCollection(Of Integer), 238MyCollection(Of Long), 238MyCollection(Of T), 237MyContainer(Of Integer), 244MyContainer(Of T), 244
■Nnamespaces, 25-28
CompilerServices, 148defining, 26-27My, 5Object Browser, 28System, 13-14System.Activator, 270System.Collection.ObjectModel, 208-211System.Collections, 239, 255System.Globalization, 171System.Object, 57-58System.Threading, 148System.Type, 269using, 27-28
namingassemblies, 91cultures, 171for exceptions, 155generic type placeholders, 240methods, 98
narrowing conversions, 13, 128-131nested classes, 43-46.NET 3.5, unhandled exceptions, 136.NET Framework, threading, 271-272.NET runtime, 1-2. See also CLR (common
language runtime)New constraint, 254New constructor, 17new features in VB 2008, 5-10
anonymous types, 9array initializers, 7extension methods, 9implicitly typed local variables, 6IntelliSense, 9lambda expressions (inline functions), 8LINQ to Objects, 8LINQ to XML, 7nullable types enhancement, 9object initializers, 6Option Infer, 10query comprehensions, 6relaxed delegates enhancement, 10
New, 58-59, 245non-nested classes, 43-45
Non-Virtual Interface (NVI) pattern, 109,318-320
Collection(Of T), 208nondeterministic destruction, 65NonGeneric method, 240Nothing, default field values, 84NotInheritable classes, 42
defaulting to, 317-318NotInheritable methods, 77NotOverridable modifier, 77NotSupportedException, 211nullable types, 249-250
enhancement in VB 2008, 9generics, 249-250
NullReferenceException, 136, 232NumberFormatInfo, 170-171, 174NVI (Non-Virtual Interface) pattern, 109,
318-320Collection(Of T), 208
■OObject, 12, 57-58Object Browser, 28object initializers, 6Object.Equals(), 344, 350-353
identity equality, 344-347overriding, 347-350overriding Object.Equals(), 347-350
Object.ToString(), 169-171format strings, 173
ObjectDisposedException, 335objects. See also reference types
boxing objects, 52cloning, reference-type best practices,
320-326 . See also ICloneableconvertible, 329-331creating, 58-62
instance constructors, 61-62New keyword, 58-59Shared constructor, 60-61
CultureInfo, 327destroying, 62-63disposable, 63-67
best practices, 334-336IDisposable interface, 63-65Using keyword, 65-67
equality, 344identity equality, 344-347overriding GetHashCode(), 350-353overriding Object.Equals(), 347-350
fields. See fieldsFinalize destructor, 3finalizers, 337-344formattable, reference-type best practices,
326-329kernel mode objects, 306LINQ to Objects, 8
■INDEX434
locking, 300-306Mutex, 305-306ReaderWriterLock, 301-303ReaderWriterLockSlim, 303-305
locking. See locking objectsordering, best practices, 331-334properties. See propertiesSystem.Object namespace, 57-58System.Thread, 272thread-hot, 338Timer, 315-316versus values, 18Win32 synchronization, 307-309
Of keyword, 237OnOPENBRACKETeventCLOSEBRACKET
method, 232OnPlay() method, 232open types, 240-241open-instance delegates, 224-227operands, mutating, 119operations, creating exception-neutral code,
147operator overloading, 117
addition (+) operator, 121-122comparison operators, 122, 125-126
Boolean, 126-129conversion operators, 129-130
CType, 130-131CType conversion operator, 130-131disadvantages, 117mirror overloads, 120mutating operands, 119operators that can be overloaded, 117-118parameter order, 120types and formats of overloaded
operators, 118-119unary, binary, and conversion operators,
117-118operators
AddressOf, 220equality, 350generic types, 257-268overloading. See operator overloadingreference types, 23-25
Option Explicit, 12-13Option Infer, 10Option Strict, 13Option Strict Off, 126-128Order By
LINQ, 375LINQ to Objects, 380-381
order of execution in multithreadedprograms, 283
ordering objects, 331-334OutOfMemoryException, 148
CERs (constrained execution regions), 150overloaded instance constructors, 36
overloaded types, 241, 244overloading methods, 74overloading operators. See operator
overloadingOverloads modifier, 102-103Overridable method, 74-77, 317
cautions when using, 77NotInheritable modifier, 77Overrides and Shadows modifiers, 75-77
Overrides modifier, 75-77overriding
Equals(), 363-367GetHashCode(), 350-353Object.Equals(), 347-350
■PP/Invoke layer, 307-308ParamArray, 73-74parameter order, overloaded operators, 120parameters of methods, 71-74
ByRef arguments, 71-73ByVal arguments, 71ParamArray, 73-74
partial classes, 48Partial keyword, 48partially named assemblies, 91PassByRef method, 72-73PassByValue method, 72passing variables
by reference (ByRef), 71-73variable numbers of parameters
(ParamArray), 73-74patterns
BeginInvoke()/EndInvoke(), 315BeginProcessData()/EndProcessData(), 310Collection(Of T), 208Disposable, 336IOU, 310, 312Non-Virtual Interface (NVI), 208ordering objects best practices, 331-334
placeholders in strings, 175PlayerUI class, 232-233PlayEvent identifier, 231PlayEventArgs class, 231pointers, 344polymorphism, interfaces, 114-115PrepareConstrainedRegions() method, 148primary constraints, 254PrintCoordinates function, 20-21Private, 37private assemblies, 92probing, 94-95ProcessResults type, 219properties, 77-80
accessors, 78declaring, 78-80indexers, 46, 48
■INDEX 435
read-only, write-only, and read-write, 79-80value variable, 78
Protected, 37-38Protected Friend, 37-38Protected Overridable method, 232Public, 37-38Public access modifier, 36Public Shared Operator methods, 118-119.
See also operator overloadingpublish-subscribe design pattern, 233publish-subscribe usage pattern, 230Pulse(), 296-300
■Qqueries
LINQ to Objects, 379-385Contains, 384From, 379Let, 383Min, Max, and Count, 381-382Order By, 380-381query evaluation, 386-389subqueries, 384-385Where, 380
LINQ to SQL, Create, Read, Update, andDelete (CRUD), 411-415
LINQ to XML, 399-403Distinct, 401From, 399-400Join, 402-403Select, 400-401Where, 401-402
query comprehensions, 6, 373-374query expressions, 6query operators, 6Queue.Clear(), 204QueueProcessor class, 274QueueUserWorkItem(), 310
■RR identifier, 242RaiseEvent statement, 233raising events, 232RankException, 200read-only fields, 81-82read-only properties, 79-80read-write properties, 79-80ReaderWriterLock, 301-303ReaderWriterLockSlim, 303, 305ReadOnlyCollection(Of T), 211real arrays versus indexers, 48reference types, 4-5, 17-18
arrays. See arraysinterfaces, 97-98New keyword, 59operators, 23-25versus value types, 18
reference-type best practices, 317checklist, 361-362cloneable objects, 320-326defaulting to NotInheritable classes,
317-318disposable objects, 334-336finalizers, 337-344formattable objects, 326-331immutable reference types, 358-360NVI pattern, using, 318-320object equality, 344
identity equality, 344-347overriding Object.Equals(), 347-350
ordering objects, 331-334overriding GetHashCode(), 350-353type safety, 353-357
reflection, 95Regex class, 186Regex.Replace method, 191-194RegexOptions type, 194-195RegionInfo, 171Register() method, 172registering custom CultureInfo types,
171-172regular expressions
searching strings, 185grouping and, 187-191Regex class, 186-187Regex.Replace method, 191-194RegexOptions type, 194-195
substitutions, 193relaxed delegates
enhancement in VB 2008, 10events, 233-235
ReleaseHandle() method, 154ReleaseMutex(), 305ReleaseReaderLock(), 302ReliabilityContractAttribute (ListSwap()
method), 150Remove() method, 221-222, 233RemoveAll() method, 221-222RemoveHandler statement, 232-233Replace() method, 187, 194replacing text for searching strings, 191-194Reset(), 215ResetAbort(), 277, 279resources
allocated, exceptions, 158-161directly held, cleaning up, 337unmanaged, 341VB
articles, 418books, 417-418web sites, 418-419
Resume(), 280, 286rethrowing exceptions, 137-139RndThreadFunc method, 287
■INDEX436
rollback behavior, 162-165Rollback() method, 162rude thread aborts, 277running console applications, 422Running state, threads, 275runtime
common language runtime. See CLR(common language runtime)
.NET runtime, 1-2RuntimeHelpers class, 148
■Ssafe points, 280SafeHandle, 150-154SafeHandle-derived types, 309safety, types
reference-types, 353-357value-types, 368, 371
saving LINQ to XML documents, 392, 398-399sealing classes, NotInheritable methods, 77searching arrays, 200searching strings with regular expressions,
185grouping and, 187-191Regex class, 186-187Regex.Replace method, 191-194RegexOptions type, 194-195
Select (LINQ), 374Select . . . Case, 30Select queries, LINQ to XML, 400-401semantics, operator overloading and, 117Semaphore, transition to kernel mode, 286SerializableAttribute, 155Set accessors, 78Set(), multidimensional arrays, 202SetMinThreads(), 310Shadows modifier, 75-77shallow copies, 320-321shared assemblies, 92-94Shared constructor, 60-61shared constructors, exceptions thrown in,
141-142shared fields, 80-81shared methods, 69-70sharing assemblies across multiple
languages, 95Shutdown method, 300shutting down threads, 300
rude thread aborts, 277Singleton pattern, 109, 242Sleep(), 275, 279, 286, 288SomeFunction method, 70SomeOperation method, 71sorting
arrays, 200objects, 331-334
SortStrategy delegate signature, 229
spin locks, 288-290SpinLockManager, 290, 293SQL. See LINQ to SQLStack.Clear(), 204StackOverflowException, 148starting threads, 272-274StartsWith() method, 185state, threads, 275-277statements, 29StaticCompute method, 222Strategy pattern
delegates and, 228-229generics, 249
StreamWriter, 290string literals, declaring, 168-169String.Clone() implementation, 324String.Compare() method, 180String.Format(), 174-177String.Intern() method, 169StringBuilder class, 184-185StringBuilder.AppendFormat(), 177StringComparer class, 180StringComparer.Create() method, 181StringComparison enumeration, 180strings, 167-168
comparing, 180-181composite, 184converting floating-point values to, 171DateTimeFormatInfo, 170, 174DBG, 173, 177format specifiers and globalization, 169
comparing strings, 180-181Console.WriteLine(), 174-175CultureInfo, 169-172custom types, 175-177format strings, 173-174ICustomFormatter, 177, 180IFormattable, 169-171Object.ToString(), 169-171String.Format(), 174-175
ICustomFormatter, 177, 180IFormatProvider, 170-171NumberFormatInfo, 171NumberFormatInfo interface, 170, 174from outside sources, working with,
181-183placeholders, 175searching with regular expressions, 185
grouping and, 187-191Regex class, 186-187Regex.Replace method, 191-194RegexOptions type, 194-195
ToString() method, 169-170strong typing, 11-13strongly (fully) named assemblies, 91structure constraints, 254Structure keyword, 15, 35
■INDEX 437
structuresClass Library project type and, 421generic, 241-242implementing interfaces, 103-105
SubmitWorkItem(), 300subqueries (LINQ to Objects), 384-385Suspend(), 277, 280, 286Suspended state, threads, 277SuspendRequested state, threads, 277sync events, 306synchronization
arrays, 200collections, 205-206
Synchronized(), 206synchronizing threads, 285-286
events, 306-307Interlocked class, 286-290kernel mode objects, 306locking objects, 300-306
Mutex, 305-306ReaderWriterLock, 301-303ReaderWriterLockSlim, 303-305
Monitor class, 291-295boxing, 295-296Pulse() and Wait(), 296-300
transitions to kernel mode, 286Win32 synchronization objects and
WaitHandle class, 307-309SyncLock keyword, 200, 205-206, 293, 296syntax
class definition. See class definitioncontrol flow constructs
If . . . Then . . . Else, 29-30Select . . . Case, 30
enumerations, 16-17iteration and looping
Continue, 33Do While and Do Until, 32-33For . . . Next, 32For Each . . . Next, 31-32
namespaces, 25-28defining, 26-27Object Browser, 28using, 27-28
reference types, 18statements, 29types, 11
converting, 19-25reference types, 17-18strong typing, 11-13type categories, 13-14value types, 14-17
value type definition. See value typedefinition
sysglobl.dll assembly, 172System, built-in types, 13-14system-generated exceptions, 136
System.Activator, 270System.Array, 197, 202System.Attribute, 95System.Char, 167System.Collections, 239, 255System.Collections.ObjectModel, 208-211System.Delegate, 220System.Exception
constructors, 155-158exception handling, 135inner exceptions, 138, 141
System.Globalization, 171System.Int32 value type, 105System.Int32.MaxValue, 184System.Monitor, 200System.Object, 12, 57-58, 197System.Reflection, 95System.String, 167
ICloneable.Clone method, 324System.Text.Encoding, 168, 181-183System.Thread, 272-273System.Threading, 148System.Type, 269System.TypeInitializationException, 141-142
■TT identifier, 241tables, LINQ to SQL . See LINQ to SQLterminating threads, 277-279TestForEquality(), 345-346thread pool, 306-310
asynchronous method calls, 311-315IOU pattern, 310-312timers, 315-316
thread-hot objects, 338thread-local storage, 281-285Thread.Abort(), 277-279Thread.AllocateDataSlot(), 283Thread.AllocateNamedDataSlot method, 283Thread.Interrupt(), 275, 279Thread.Join(), 275, 280Thread.Priority property, 274Thread.ResetAbort(), 277, 279Thread.Resume(), 280, 286Thread.Sleep(), 275, 279, 286, 288Thread.Suspend(), 277, 280, 286ThreadAbortException, 136, 148, 277-279ThreadFunc method, 273threading, 271
managed threads, 271.NET Framework, 271-272order of execution in multithreaded
programs, 283primary threads, 271worker threads, 271
Threading.Interlocked class, 286ThreadInterruptedException, 275, 279
■INDEX438
ThreadPool class. See thread poolthreads
background, 280-281, 315foreground, 280-281halting and waking, 279-280rude thread aborts, 277safe points, 280shutting down, 300starting, 272-274states, 275-277synchronizing, 285-286
events, 306-307Interlocked class, 286-290kernel mode objects, 306locking objects, 300-306Monitor class, 291, 293-300transitions to kernel mode, 286Win32 synchronization objects and
WaitHandle class, 307-309terminating, 277-279ThreadPool class. See thread poolwaiting for threads to exit, 280
ThreadStart delegate, 272-273ThreadState enumeration, 275ThreadStaticAttribute attribute, 281Throw statements, 136
exception-neutral code and, 143rethrowing exceptions, 137-139throwing exceptions, 136
throwing exceptions, 136exceptions thrown in Finally blocks,
139-140rethrowing, 137-139Throw statements, 136
timers, 315-316TInput placeholder identifier, 245TLSClass, 282TLSFieldClass, 282ToString(), 169-170, 326-329
Object keyword, 58String.Format(), 175
ToType(), 330TOutput placeholder identifier, 245transitions to kernel mode, avoiding via
Threading.Interlocked class, 286translating exceptions, 137-139Try statements
exception handling, 134-136, 159-161exception-neutral code and, 143-146
Try/Finally blocksdisposable objects, 65iteration, 215Using statements, 67
TryCast, 22type arguments, 105-106type conversion, 248-249, 257-268type inference (LINQ), 375-376
type parameters, 105-106, 237type safety
reference-types, 353-357value-types, 368, 371
TypeConverter, 331TypeInitializationException, 141-142, 155TypeOf, 21, 23-24types, 11
anonymous types, 9arrays. See arrayscategories, 13-14closed, 240-241collections. See collectionscommon type system (CTS), 3constructed, generics, 240, 251, 268-270converting, 19-20
boxing conversions, 22-23Convert class, 20CType, 20-21DirectCast and TryCast, 22explicit conversion, 19-20reference type operators, 23-25widening conversions, 13, 19
custom CultureInfo types, 171-172custom types, string formatting, 175, 177enclosing type, 119Func (LINQ), 378generic
accessibility of types, 251classes and structures, 241-242collections, 255-257constraints, 251-255creating constructed types dynamically,
268-270declaring, 237-240delegates, 244-248interfaces, 242methods, 243-245nullable types, 249-250type conversion, 248-249, 257-268type definitions and constructed types,
240type placeholder naming conventions,
240type safety, 238-240
ISomeInterface, 238-239nullable, 249-250
enhancement in VB 2008, 9open, 240-241overloaded, 241, 244ProcessResults, 219reference types, 1-5, 17-18
New keyword, 59versus value types, 18
reference-type best practices, 317checklist, 361-362cloneable objects, 320-322, 324-326
■INDEX 439
convertible objects, 329-331defaulting to NotInheritable classes,
317-318disposable objects, 334-336finalizers, 337-344formattable objects, 326-329immutable reference types, 358-360NVI pattern, using, 318-320object equality, 344-350ordering objects, 331-334overriding GetHashCode(), 350-353type safety, 353-357
SafeHandle-derived types, 309strong typing, 11-13value types, 1-5, 14-16
enumerations, 16-17New keyword, 58versus reference types, 18
value-type best practices, 362-372checklist, 371-372implementing type-safe forms, 368, 371overriding Equals(), 363, 365, 367
■Uunary operators, overloading, 117-118unboxing, 52-57
efficiency of, 56-57generics, 239
undeclared variables, 12unhandled exceptions in .NET 3.5, 136UnhandledExceptionEventArgs, 136Unicode character arrays, 181-183Unicode UTF-16 character arrays, 181unmanaged resources, 341unsafe code in C# 3.0, 2Unstarted state, threads, 275untyped variables, 12updating table records (LINQ to SQL), 413-
414UpgradeToWriterLock(), 302user-defined value types, 15Using keyword, 65, 67, 336
exception handling, 161-162utilities
gacutil.exe, 94IL Disassembler. See IL Disassembler (IL
DASM)
■Vvalue keyword, 233value type definitions, 48-51
constructors, 49-50definitions. See value type definitionsfinalizers, 51interfaces, 51Me, 50-51
value types, 4-5, 14-16boxing/unboxing, 52-57design checklist, 372enumerations, 16-17implementing interfaces, 105New keyword, 58versus reference types, 18
value variable, 78value-type best practices, 362-372
checklist, 371-372implementing type-safe forms, 368, 371overriding Equals(), 363-367
valuesconverting floating-point values to strings,
171versus objects, 18
variables. See also typesimplicitly typed local variables, 6iterator variables, 31Option Explicit, 12-13Option Strict, 13passing
by reference (ByRef), 71-73variable numbers of parameters
(ParamArray), 73-74reference, equality between, 344-345strong typing, 11-13undeclared, 12untyped, 12
VB 2008CLR garbage collection, 3common type system, 3-5Hello World! program, 5new features, 5-10
anonymous types, 9array initializers, 7extension methods, 9implicitly typed local variables, 6IntelliSense, 9lambda expressions (inline functions), 8LINQ to Objects, 8LINQ to XML, 7nullable types enhancement, 9object initializers, 6Option Infer, 10query comprehensions, 6relaxed delegates enhancement, 10
versusC# 3.0, 2-3VB6, 3
VB 2008.NET runtime, 1-2VB compiler, 85-87versioning assemblies, 95
■INDEX440
■WWaitAll(), 307WaitAny(), 307WaitHandle class, 306-309waiting (threads), 280, 306. See also Monitor
classavoiding race conditions, 285EventWaitHandle, 286Monitor.Wait(), 275, 296-298, 300reentrant wait mechanisms, 290Thread.Join(), 275, 277, 280transition to kernel mode, 286WaitHandle class, 306-309waiting for exit, 280WaitSleepJoin state, 275-277
WaitOne(), 305-306WaitSleepJoin state, threads, 275waking threads, 279-280Where (LINQ), 375Where queries
LINQ to Objects, 380LINQ to XML, 401-402
widening conversions, 13, 19, 129-131Win32 functions, 153Win32 Synchronization objects, 307-309Win32Heap example
modified, 341, 343with finalizer, 338-340
write-only properties, 79-80WriteLine(), 174-175writing exception-neutral code, 143
constrained execution regions (CERs),148-150
critical finalizers and SafeHandle, 150-154rollback behavior, 162-165structure of, 143-148
writing exception-safe code, 133
■XXCopy deployment, 92XML
axis properties, 390LINQ to XML. See LINQ to XML
■INDEX 441