9.7 KiB
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 anint[]
. That's far better than storing the data inobject[]
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: