In the .Net Framework 1.x most of the collection classes store a data of type "System.Object", so you can store any types of data in the collection object or many types in the same collection object. This makes the addition of new items very easy, but when you need to extract a stored data from the collection you will first need to cast it back to its original data type. This cast had a performance impact especially when you are going to deal with the stored data repeatedly. It slows down your code plus making it less readable.
Dim List As New System.Collections.ArrayList
List.Add("ABab")
List.Add(123)
List.Add(10.3)
List.Add("ABab")
List.Add(123)
List.Add(10.3)
In the .Net Framework 2.0 the notion of generic is introduced to avoid the problem of casting as a source of performance drain and to allow the compiler to catch any try to store a different type of data in the specified collection at design time.
Dim List As New System.Collections.Generic.List(Of String)
List.Add("Aa")
List.Add("Bb")
List.Add("Cc")
List.Add("Aa")
List.Add("Bb")
List.Add("Cc")
It is recommended to use generic collections. The only reason you may need to use non-generic collections is for legacy purposes or if you need your code to work with older versions of the .Net Framework. If you need to store different types of data in a collection you can still use generic collections, all what you need is to find a common base between the stored data types. In the worst case you can use the System.Object as the generic type parameter.
Dim List As New System.Collections.Generic.List(Of System.Object)
No comments:
Post a Comment