views:

7086

answers:

5

What is the difference between ArrayList and List in VB.NET

+1  A: 

List can make use of generics so that only objects of specific types can be placed into it, so that you can have extra type checking and so that you can cut down on processing time due to boxing and unboxing. Arraylist cannot use this. In almost all cases, you'll want to use a List rather than an Arraylist.

Kibbee
Generics was introduced with .NEt 2.0 but these classes existed before that too. Is there a difference in the way these classes are internally written.
MOZILLA
Unless there is some other List class that I'm unaware of, then this is wrong. The full namespace of List is System.Collections.Generic.List, which means it was pretty much specifically added for use with Generics.
Kibbee
+14  A: 

ArrayLists are essentially deprecated as they're untyped - you need to use casts with them - and they're slower and less space efficient for value types because they require the items to be boxed.

Generic lists were introduced with .Net 2.0 and are the way to go. Often a List is better than an array, with few downsides.

As these collections are part of the .Net Base Class Library, this advice also applies to C# and to any .Net language which supports generics - it's not specific to VB.NET.

Mike Scott
+4  A: 

List is a generic implementation of ArrayList. ArrayList stores all objects as System.Object which you need then cast to appropriate type. ArrayLists are heterogenous, List can store only one type of objects - that type supplied as its generic parameter.

List<string> strList; // can store only strings
List<int> intList; // can store only ints
ArrayList someList; // can store anything
arul
Of course, you technically could always make a list that stored type "Object" and store anything in it, because everything inherently inherits from object.
Kibbee
And everyone would point and laugh at you
Will
+2  A: 

ArrayList allows you to write this:

Dim customers as new ArrayList
Dim c as new Customer
Dim m as new Manager
customers.Add(c)
customers.Add(m)

'This will cause an exception '  
For each c as Customer in customers
console.writeline(c.Name)
Next

A List(of Customer) allows only object of Customer type and types that inherit from Customer, so you cannot make such mistakes.

Even if you need to put objects of unrelated types in the same collection, a List(Of Object) is a better choice as it makes explicit that you are dealing with different types.

ggf31416
+1  A: 

ArrayLists are even more space inefficient when used on 64bit to store primitive elements because of the 64bit wide memory references as opposed to 32bit references on 32bit machines, and boxing.

See this for more details: http://blogs.msdn.com/joshwil/archive/2004/04/13/112598.aspx

xslr