4.0 Introduction
Generics, a long-awaited feature, came to the end with the advent of the C # 2.0 compiler. Generics are a very useful feature that makes your code leaner and more productive. These will be described in detail in Tip 4.1. The advent of generics allows you to write more powerful applications, but it needs to be used correctly. If you consider converting Arraylist,queue,stack and Hashtable objects to use the appropriate generic version, you can read the tips 4.4,4.5 and 4.10. When you read it, you will find that the change is not necessarily simple, and may even be no longer intended to change.
Other tips in this chapter relate to other generic classes contained in the. NET Framework 2.0, such as Tip 4.6. Other tips describe the operations of some generic classes, such as Secret 4.2,4.8 and 4.13.
4.1 Deciding when and where to use generics
Problem
You want to use generics within a new project, or you want to convert a Non-generic class in an existing project to an equivalent generic version. But you don't understand why you do this, and you don't know which Non-generic class should be converted to a generic class.
Solution
To decide when and where to use generics, you need to consider the following several events:
• Do you use a type that contains or operates an unspecified data type, such as a collection type? If so, creating a generic type will provide more benefits. If your type only operates on a single specified type, then there is no need to create a generic class.
L If your type will manipulate the value type, then a boxing and unboxing operation will be generated, and you should consider using generics to prevent boxing and unboxing operations.
The strong type checking of generic types helps to quickly find errors (i.e., compile-time rather than run-time), thereby shortening the bug-fix cycle.
• Is there a "code bloat" problem when writing multiple classes to manipulate multiple data types (such as a ArrayList store only Streamreaders and another storage streamwriters)? It's easy to write code once and make it work on multiple data types.
L generics make the code clearer. By eliminating code bloat and enforcing checks, your code becomes easier to read and understand.
Discuss
Many times, the use of generic types will benefit you. Generics make code reuse more efficient, perform faster, enforce type checking, and get more readable code.
Read reference
The "Generics Overview" and "benefits of generics" topics in the MSDN documentation.