Section 10.1. What Are Generics?


10.1. What Are Generics?

Visual Basic 2005 includes a new feature named generics, built upon features added to Version 2.0 of the .NET Framework. Generics allow you to add enforced strong typing within an otherwise weakly typed type (class, structure, interface, or delegate) or its methods (functions and sub procedures).

Before generics, if you wanted to use the Stack class to manage a set of Integer values, and only Integer values, you had a few options.

  • Create a brand new collection-type class named IntegerStack that works just like the Stack class but is hardcoded to use Integer values only. It would include the Stack class's Push and Pop methods, but they would only deal with Integer value types. While this would solve your problem, it wouldn't be fun to program. You would essentially rewrite all of the code in the existing Stack class from scratch. If you later wanted to develop a similar class for strings, you would have to do it all again, this time enforcing the data type to be String.

  • Create a new class named IntegerStack that derives from or wraps the functionality of the Stack class. This class would have its own new methods that enforce the Integer restriction, but each of those methods would, in turn, call the standard Stack class methods. This is a little better, since you wouldn't have to recode the entire Stack logic. But you would still have to do it again for String data. And all of this wrapping and type-casting between System.Object and Integer can't be that efficient.

  • Just use the existing Stack class and hope that only integers are used. Unfortunately, this doesn't really solve the problem.

Generics solve this problem by allowing an instance of a class to look like it was written just for a restricted data type. All enforcement occurs at compile time, so the program is also more efficient, since the data does not have to be converted to System.Object and back again all the time. Visual Studio also uses the generic definitions to enhance the IntelliSense available when working with generics -enabled types.

Generics are similar to a feature called templates in the C++ language, although generics are somewhat easier to use and do not support all of the features available with templates.




Visual Basic 2005(c) In a Nutshell
Visual Basic 2005 in a Nutshell (In a Nutshell (OReilly))
ISBN: 059610152X
EAN: 2147483647
Year: 2004
Pages: 712

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net