Before .NET 2005(This is still supported in .NET 2005 as well) when we define a collection we use the syntax:
private col as new Collection
So if i am going to use this collection to add and retrieve Customers i have to use the syntax:
col.Add(New Customer())
Dim cust As Customer = CType(col.Item(0), Customer)
But if i already know i am going to use this collection only for to store Customers this casting is a real pain. And the compiler will do nothing to prevent me from storing a String or some other object type in this collection(A run time error will be throw when i try to cast it to Customer)
With .NET 2005 you have a special set of collection classes under the Collections.Generic namespace. With this i can define a collection as:
private col as new Collection(Of Customer)
Notice the new keyword 'Of', this indicates this collection will be used to store only Customer objects.
col.Add(New Customer())
Dim cust As Customer = col.Item(0)
No more unnecessary casting since the return types are of the Customer type and not the Object type. The compiler will detect if you are trying to store some other types other than what is defined. And what more you can also define and use Generics in your own classes and constructs but i'll save that for another blog
No comments:
Post a Comment