Question array list and generics

vi2psn

New member
Joined
Dec 20, 2010
Messages
1
Programming Experience
Beginner
quick question on difference between arraylist and generics.

i know boxing and unboxing part in arraylist but question is if i define only string in arraylist then there is no question of boxing or unboxing.
s wht will be difference.
 
Generics means generic type definition, and allow strongly typed members for any compile-time assigned type. The generic alternative to ArrayList is List(Of T) where T is the allowed type of items in the list. The equivalent type to ArrayList is a List(Of Object). As an example lets say you have a ArrayList (items) containing string values and you want to get the first one:
VB.NET:
Dim first As String = items(0)
This code result in this compiler error:
Option Strict On disallows implicit conversions from 'Object' to 'String'.
The fix would be to convert (cast) the item to the correct type, for example with CStr function to convert from Object to String.
Whereas if you items is a List(Of String) the code is valid because the returned property value will be type String.

Similar when putting items into the ArrayList there will be no compile time validation since Object type will allow anything. Only at runtime the errors will emerge if the code erroneously put the wrong type of item in. While with a List(Of String) you will only be allowed to write type safe code that explicitly adds String type values.

Generics has many uses other than for collections, and since .Net 2.0 they have been included in many parts of the .Net libraries.
 
Back
Top