Collection Classes in .net - the Generic List
This is the third part of an article on collection classes in .net with C#. This part covers the Generic List.
For the first part see http://www.audacs.co.uk/ViewPage.aspx?PageID=512
For the next part on the HashTable see http://www.audacs.co.uk/ViewPage.aspx?PageID=515
Ok so what is a Generic List?
Well it is very simillar to an ArrayList but it uses generics to make the types well known and safe at compile time.
Before generics we used to have may classes which would use objects in order to allow them to be flexible. The ArrayList for example is a collection of objects and so you can store anything in there - a collection of string, ints, customers, database connections - absolutley anything since all classes ultimatley inherit from System.Object.
This is good but it does have a few downsides. First of all when retrieving items out of an ArrayList we have to then cast them to their specific class in order to use them. This leads to extra code and extra resources. Also though it can lead to runtime errors if one of the objects in the collection isn't the expected type when a cast is performed.
To solve these problems Microsoft introduced generics. A generic list is the generic version of an ArrayList. We might use one as follows
So you can see that it is used very much like an old ArrayList other than when we declare it me put the type which the collection will hold within the angle brackets.
We then get compile time type checking. If we have code which tries to add some other type to the list then we will get a compile time error rather than a runtime one - somehting which is clearly much more preferable.
There are many many other places where generics are used of course but that is beyond the scope of theis article.
So if you are familliar with an ArrayList then you should be comfortable with a Generic List and theres not really much else to say really.
For the next part on the HashTable see http://www.audacs.co.uk/ViewPage.aspx?PageID=515