Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generics and System.Collections

After moving to .NET 2.0+ is there ever a reason to still use the systems.Collections namespace (besides maintaining legacy code)? Should the generics namespace always be used instead?

like image 388
leora Avatar asked Nov 30 '08 11:11

leora


People also ask

What are generics and collections?

The generic collections disable the type-casting and there is no use of type-casting when it is used in generics. The generic collections are type-safe and checked at compile-time. These generic collections allow the datatypes to pass as parameters to classes.

What is the generic and non-generic collections?

A Generic collection is a class that provides type safety without having to derive from a base collection type and implement type-specific members. A Non-generic collection is a specialized class for data storage and retrieval that provides support for stacks, queues, lists and hashtables.


1 Answers

For the most part, the generic collections will perform faster than the non-generic counterpart and give you the benefit of having a strongly-typed collection. Comparing the collections available in System.Collections and System.Collections.Generic, you get the following "migration":

    Non-Generic               Generic Equivalent
    ------------------------------------------------------------
    ArrayList                 List<T>
    BitArray                  N/A
    CaseInsensitiveComparer   N/A
    CollectionBase            Collection<T>
    Comparer                  Comparer<T>
    DictionaryBase            Dictionary<TKey,TValue>
    Hashtable                 Dictionary<TKey,TValue>
    Queue                     Queue<T>
    ReadOnlyCollectionBase    ReadOnlyCollection<T>
    SortedList                SortedList<TKey,TValue>
    Stack                     Stack<T>

    DictionaryEntry           KeyValuePair<TKey,TValue>

    ICollection               N/A (use IEnumerable<T> or anything that extends it)
    IComparer                 IComparer<T>
    IDictionary               IDictionary<TKey,TValue>
    IEnumerable               IEnumerable<T>
    IEnumerator               IEnumerator<T>
    IEqualityComparer         IEqualityComparer<T>
    IList                     IList<T>

ICollection is immutable (no members to change the contents of the collection) while ICollection<T> is mutable. This makes the interfaces similar in name only while ICollection and IEnumerable<T> differ by very little.

From this list, the only non-generic classes that don't have a generic counterpart are BitArray and CaseInsensitiveComparer.

like image 52
Scott Dorman Avatar answered Nov 16 '22 02:11

Scott Dorman