What's the point in C # should we give preference to using List
instead of ArrayList
?
What's the point in C # should we give preference to using List
instead of ArrayList
?
Because List
is generic and ArrayList
is not. The data type of ArrayList
is a object
, ie it can by anything in it. In static languages this is not appropriate, you lose type security, you can no longer trust the contents of the list. Already List<T>
determines what type you can put on it , then all of the code is trusted that it will only have elements of that particular type and derived types of it that are obviously compatible with this type. The compiler itself can ensure type security.
It's not just security, it's performance, too. This prevents casting and
List<T>
is a generic class. It supports storing values of a specific type without the need to force from or to object
.
ArrayList
simply stores object references. As a generic collection, List<T>
implements IEnumerable<T>
generic interface and can be easily used in LINQ
(without needing Cast
or OfType
).
ArrayList
belongs to the days when C # had no generics. It is depreciated in favor of List<T>
. You should not use ArrayList
in a new code that targets .NET > = 2.0, unless you have to connect to an old API that uses it.
reference: stackoverflow.com/a/2309699/4190610