Skip to content
This repository has been archived by the owner on Nov 28, 2020. It is now read-only.

Latest commit

 

History

History
126 lines (116 loc) · 9.68 KB

DE0006.md

File metadata and controls

126 lines (116 loc) · 9.68 KB

DE0006: Non-generic collections shouldn't be used

Motivation

When .NET was created, generic data types didn't exist, which is why the collection types in the System.Collections namespace are untyped. However, since then, generic data types were introduced and thus a new set of collections were made available in the System.Collections.Generic and System.Collections.ObjectModel namespaces.

Recommendation

For new code, you shouldn't use non-generic collections:

  • Error prone: since non-generic collections are untyped, it requires frequent casting between object and the actual type you're expecting. Since the compiler can't check that your types are consistent, it's easier to put the wrong type in the wrong collection.

  • Less performant: generic collections have the advantage that value types don't have to be boxed as object. For instance, a List<int> stores its data in an int[]. That's far better than storing the data in object[] as that requires boxing.

The following table shows how the non-generic collection types can be replaced by their generic counterparts from the System.Collections.Generic or System.Collections.ObjectModel namespaces:

Type Replacement
ArrayList List<T>
CaseInsensitiveComparer StringComparer.OrdinalIgnoreCase
CaseInsensitiveHashCodeProvider StringComparer.OrdinalIgnoreCase
CollectionBase Collection<T>
Comparer Comparer<T>
DictionaryBase Dictionary<TKey, TValue> or KeyedCollection<TKey, TItem>
DictionaryEntry KeyValuePair<TKey, TValue>
Hashtable Dictionary<TKey, TValue>
Queue Queue<T>
ReadOnlyCollectionBase ReadOnlyCollection<T>
SortedList SortedList<TKey, TValue>
Stack Stack<T>