Advantages of Generics
By allowing you to specify the specific types acted on by a generic class or method, the generics feature shifts the burden of type safety from you to the compiler. There is no need to write code to test for the correct data type, because it is enforced at compile time. The need for type casting and the possibility of run-time errors are reduced.
Generics provide type safety without the overhead of multiple implementations. For example, you can create a linked list of strings with the following variable declaration:
There is no need to inherit from a base type and override members. The linked list is ready for immediate use. Seeand for the generic collection types provided by the .NET Framework.
In addition to type safety, generic collection types generally perform better for storing and manipulating value types because there is no need to box the value types.
Generic delegates enable type-safe callbacks without the need to create multiple delegate classes. For example, thegeneric delegate allows you to create a method that implements your own search criteria for a particular type and to use your method with methods of the type such as , , and .
Generic delegates also can be used in dynamically generated code without requiring the generation of a delegate type. This increases the number of scenarios in which you can use lightweight dynamic methods instead of generating entire assemblies. For more information, seeand .
In many cases, the Visual Basic, Visual C++, and C# compilers are capable of determining from context the types used by a generic method call, greatly simplifying the syntax for using generic methods. For example, the following code shows the short and long forms for calling thegeneric method to search an array of strings. In the short form, the compilers infer the correct type parameter from the types of the method arguments.
int index = Array.BinarySearch(myArray, "test string"); int index = Array.BinarySearch<string>(myArray, "test string");