Friday, June 8, 2012

Arraylist Vs List collection in VB.net

ArrayList:

arraylist is non generic type collection from name space (system.collection)
by default it can contain  any type  means it accept system.object (every type reference or value type derived from system.object class).
For Example:

Module Module1
    Sub Main()
        Dim lst As New ArrayList
        lst.Add("yousuf")
        lst.Add(2)
        Dim STR() As String = {"ashar", "kamran"}
        lst.AddRange(Str)
        For Each Obj As Object In lst
            Console.WriteLine(Obj)
        Next
        Console.ReadLine()
    End Sub

End Module

Out Put:
yousuf
2
ashar
kamran


LIST:

list is  generic type collection from name space(system.collection.generic)
 it can contain a specific type means that its type safe so that you can't insert an integer and string in same list.
Dim lst As New List(Of  T)
where "T" can be integer ,string or any type.  if you will assign T as "Object" then it will work same as non generic type.
For Example:

Module Module1
    Sub Main()
        Dim lst As New List(Of String)
        lst.Add("yousuf")
         Dim STR() As String = {"yasir", "kamran"}
        lst.AddRange(Str)
        For Each Obj As Object In lst
            Console.WriteLine(Obj)
        Next
        Console.ReadLine()
    End Sub

End Module

Out Put:
yousuf
ashar
kamran


I will prefer you to use List instead of arraylist because it is type safe and second it will not cast object type  in to appropriate type so performance is better .






 

No comments:

Post a Comment