What is the difference between ArrayList
and List<>
in C#?
Is it only that List<>
has a type while ArrayList
doesn't?
What is the difference between ArrayList
and List<>
in C#?
Is it only that List<>
has a type while ArrayList
doesn't?
I think, the differences between
ArrayList
andList<T>
are:List<T>
, where T is value-type is faster thanArrayList
. This is becauseList<T>
avoids boxing/unboxing (where T is value-type).ArrayList
used just for backward compatibility. (is not a real difference, but i think it is important note).ArrayList
thenList<T>
ArrayList
hasIsSynchronized
property. So, It is easy to create and use syncronisedArrayList
. I didin't foundIsSynchronized
property forList<T>
. Also Keep in mind this type of synchronization is relatively inefficient, msdn):ArrayList
hasArrayList.SyncRoot
property which can be used for syncronisation (msdn).List<T>
hasn'tSyncRoot
property, so in the following construction you need to use some object if you useList<T>
:Using
List<T>
you can prevent casting errors. It is very useful to avoid a runtime casting error.Example:
Here (using
ArrayList
) you can compile this code but you will see an execution error later.If you use
List
, you avoid these errors:Reference: MSDN
To add to the above points. Using
ArrayList
in 64bit operating system takes 2x memory than using in the 32bit operating system. Meanwhile, generic listList<T>
will use much low memory than theArrayList
.for example if we use a
ArrayList
of 19MB in 32-bit it would take 39MB in the 64-bit. But if you have a generic listList<int>
of 8MB in 32-bit it would take only 8.1MB in 64-bit, which is a whooping 481% difference when compared to ArrayList.Source: ArrayList’s vs. generic List for primitive types and 64-bits
Yes, pretty much.
List<T>
is a generic class. It supports storing values of a specific type without casting to or fromobject
(which would have incurred boxing/unboxing overhead whenT
is a value type in theArrayList
case).ArrayList
simply storesobject
references. As a generic collection,List<T>
implements the genericIEnumerable<T>
interface and can be used easily in LINQ (without requiring anyCast
orOfType
call).ArrayList
belongs to the days that C# didn't have generics. It's deprecated in favor ofList<T>
. You shouldn't useArrayList
in new code that targets .NET >= 2.0 unless you have to interface with an old API that uses it.Another difference to add is with respect to Thread Synchronization.
More info here Thread Synchronization in the .Net Framework
Using "List" you can prevent casting errors. It is very useful to avoid a runtime casting error.
Example:
Here (using ArrayList) you can compile this code but you will see an execution error later.