Compartilhar via


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:

Dim llist As New LinkedList(Of String)
LinkedList<string> llist = new LinkedList<string>();
LinkedList<String^>^ llist = gcnew LinkedList<String^>();

There is no need to inherit from a base type and override members. The linked list is ready for immediate use. See System.Collections.Generic and System.Collections.ObjectModel 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, the Predicate generic 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 Array type such as Find, FindLast, and FindAll.

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, see How to: Define and Execute Dynamic Methods and DynamicMethod.

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 the BinarySearch generic 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.

Dim index As Integer = Array.BinarySearch(myArray, "test string")
Dim index As Integer = _
    Array.BinarySearch(Of String)(myArray, "test string")
int index = Array.BinarySearch(myArray, "test string");
int index = Array.BinarySearch<string>(myArray, "test string");
int index = Array::BinarySearch(myArray, "test string");
int index = Array::BinarySearch<String^>(myArray, "test string");

See Also

Reference

System.Collections.Generic
System.Collections.ObjectModel

Concepts

Overview of Generics in the .NET Framework