Generics are part of the .NET Framework’s type system that allows you to define a type while leaving some details unspecified. Instead of specifying the types of parameters or member classes, you can allow code that uses your type to specify it. This allows consumer code to tailor your type to its own specific needs.
The .NET Framework version 2.0 includes several generic classes in the System.Collections. Generic namespace, including Dictionary, Queue,SortedDictionary, and SortedList. These classes work similarly to their nongeneric counterparts in System.Collections, but they offer improved performance and type safety.
Generics offer two significant advantages over using the Object class:
-
Reduced run-time errors: The compiler cannot detect type errors when you cast to and from the Object class. For example, if you cast a string to an Object class and then attempt to cast that Object to an integer, the compiler will not catch the error. Instead, the runtime will throw an exception. Using generics allows the compiler to catch this type of bug before your program runs. Additionally, you can specify constraints to limit the classes used in a generic, enabling the compiler to detect an incompatible type.
-
Improved performance: Casting requires boxing and unboxing, which steals processor time and slows performance. Using generics doesn’t require casting or boxing, which improves run-time performance.