Partilhar via


When to Use Generic Collections 

Using generic collections is generally recommended, because you gain the immediate benefit of type safety without having to derive from a base collection type and implement type-specific members. In addition, generic collection types generally perform better than the corresponding nongeneric collection types (and better than types derived from nongeneric base collection types) when the collection elements are value types, because with generics there is no need to box the elements.

The following generic types correspond to existing collection types:

  • List is the generic class corresponding to ArrayList.

  • Dictionary is the generic class corresponding to Hashtable.

  • Collection is the generic class corresponding to CollectionBase. Collection can be used as a base class, but unlike CollectionBase it is not abstract, making it much easier to use.

  • ReadOnlyCollection is the generic class corresponding to ReadOnlyCollectionBase. ReadOnlyCollection is not abstract, and has a constructor that makes it easy to expose an existing List as a read-only collection.

  • The Queue, Stack, and SortedList generic classes correspond to the respective nongeneric classes with the same names.

Additional Types

There are several generic collection types that do not have nongeneric counterparts:

  • LinkedList is a general-purpose linked list that provides O(1) insertion and removal operations.

  • SortedDictionary is a sorted dictionary with O(log n) insertion and retrieval operations, making it a useful alternative to SortedList.

  • KeyedCollection is a hybrid between a list and a dictionary, which provides a way to store objects that contain their own keys.

Additional Functionality

Some of the generic types have functionality not found in the nongeneric collection types. For example, the List class, which corresponds to the nongeneric ArrayList class, has a number of methods that accept generic delegates, such as the Predicate delegate that allows you to specify methods for searching the list, the Action delegate that represents methods that act on each element of the list, and the Converter delegate that lets you define conversions between types.

The List class allows you to specify your own IComparer generic interface implementations for sorting and searching the list. The SortedDictionary and SortedList classes also have this capability, and in addition allow the comparers to be specified when the collection is created. In similar fashion, the Dictionary and KeyedCollection classes allow you to specify your own equality comparers.

See Also

Concepts

Overview of Generics in the .NET Framework

Other Resources

Commonly Used Collection Types