|
xxx
Generic Collections
by Ryan Olshan
You should use Generic collections in .NET 2.0 instead of non-Generic collections, due
to the addition of overhead that is incurred when casting objects in non-Generic collections. Generic collections live in the namespace System.Collections.Generic.
Non-Generic and Generic Collection Equivelents
| Non-Generic | Generic |
| ArrayList | List<Value> |
| CollectionBase | Collection<Value> |
| DictionaryBase | N/A (implement IDictionary<Key, Value> |
| HashTable | Dictionary<Key, Value> |
| ICollection | N/A (use IEnumerable<Value> or anything that extends it) |
| IEnumerable | IEnumerable<Value> |
| IList | IList<Value> |
| Queue | Queue<Value> |
| ReadOnlyCollectionBase | ReadOnlyCollection<Value> |
| SortedList | SortedList<Key, Value> |
| Stack | Stack<Value> |
| N/A | ICollection<Value> |
| N/A | KeyedCollection<Key, Item> |
| N/A | LinkedList<Key, Value> |
| N/A | SortedDictionary<Key, Value> |
Non-Generic Collection Example: ArrayList
In .NET 1.x, a collection of values could be stored in a collection. The demo below is using an ArrayList.
VB.NET
Dim arrayNames As new ArrayList()
arrayNames.Add("Bob")
arrayNames.Add("Sally")
arrayNames.Add("John")
C#
ArrayList arrayNames = new ArrayList();
arrayNames.Add("Bob");
arrayNames.Add("Sally");
arrayNames.Add("John");
Values added to any collection are added as type object. In order to retrieve a value from the ArrayList, we access it by its index:
VB.NET
Dim strName As string
strName = arrayNames(1)
C#
string strName;
strName = (string)arrayNames[1];
Because the values are stored as objects they need to be type casted. In VB.NET, this is done automatically using late binding. In C#, you have to implicitly cast the type. Both operations add overhead.
Generic Collection Example: List
In .NET 2.0, a generic collection can be used. When the collection is instantiated, the datatype is declared. As a result, the values are strongly typed as the datatype of the list/values are known at runtime. In the example below, we use the Generic collection equivelent of an ArrayList.
VB.NET
Dim listNames As new List(Of String)
listNames.Add("Bob")
listNames.Add("Sally")
listNames.Add("John")
C#
List<string> listNames = new List<string>;
listNames.Add("Bob");
listNames.Add("Sally");
listNames.Add("John");
Because no type casting is involved, we can access a value in the List collection as follows:
VB.NET
Dim strName As string
strName = listNames(1)
C#
string strName;
strName = listNames[1];
 |  |  |
 |
There are many worthy charities!!. But perhaps help starving children in Africa or South America AND help Charles too.
a $5 tip buys him lunch at McDonalds,
a $20 tip buys his kid Hitoshi a new computer game,
a $39 tip buys his daughter Michiko a few nice outfits.
See our donor list.
|  |
 |  |  |
|
|
|
|