Now the compiler has everything it needs to
enforce strong type safety.
nNote Added type safety at compile time is a good thing because it??™s better to capture bugs based on type
mismatches at compile time rather than later at run time.
The previous example shows how to use generics for better type safety. However, you
haven??™t gained much yet from an efficiency standpoint. The real efficiency gain comes into
play when the type argument is a value type. Remember that a value type inserted into a collection
in the System.Collections namespace, such as ArrayList, must first be boxed, since
the ArrayList maintains a collection of System.Object types. An ArrayList meant to hold
nothing but a bunch of integers suffers from severe efficiency problems because you must box
and unbox the integers each time you insert and reference or extract them from the ArrayList,
respectively. Also, an unboxing operation in VB is normally formed with an IL unbox operation
paired with a copy operation on the value type??™s data. Generics comes to the rescue and stops
the box/unbox cycle. As an example, compile the following code, and then load the assembly
into the IL Disassembler (IL DASM) to compare the IL generated for each of the methods that
accepts a stack:
Imports System
Imports System.
Pages:
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391