Wely

wel = new Geeks();
See also: Other Geeks@INDC

Have you use Generic’s collection?

We often need collection in our programming. To implement collection, we have two choices: fixed-length collection which is familiarly "array" and dynamic length collection. One of the popular dynamic collections is ArrayList. ArrayList (actually Queue, Stact, other collection also) accepts object type, so you could add any type object in it. This is both advantages and disadvantage of them. (In this case, we will take ArrayList as example).

Disadvantage? Yeah, it is not type-safety. Check this out!

Suppose we are going to have a collection of integer using ArrayList:

ArrayList arr = new ArrayList();

arr.Add(1);

arr.Add(2);

arr.Add("3");

arr.Add(4);

foreach (int a in arr)

{

Console.WriteLine(a);

}

Notice that when I code arr.Add("3"), there was just fine. No compile time error. But when I run it.

Yeah, InvalidCastException. Runtime error. Why? This is because when we enumerate there were some invalid type occurred. We actually expect to add a collection of integer, but eventhough I add a string, the ArrayList accept it without any complain.

.NET team aware that it would be better to have the compile time error, rather than runtime error. So, .NET 2.0 introduced us Generic.

The goal of Generics is:

  • Type safety
  • No Boxing and UnBoxing, because it takes some resources to do that.

In this sample, I will not show you too funky feature, I will just introduce a generic version of ArrayList, which is List<>. Here we go J

Look! I define my List<> just to accept integer. When I add integer, it just work fine, but when I add others type (in this case integer), the compiler will complain. The compile time error. Compiler will tell, "wrong type, bro! Fix it first".

Other generic collection are also available:

Type

Generic Type

ArrayList

List<>

Queue

Queue<>

Stack

Stack<>

Hashtable

Dictionary<>

SortedList

SortedList<>

ListDictionary

Dictionary<>

HybridDictionary

Dictionary<>

OrderedDictionary

Dictionary<>

SortedDictionary

SortedDictionary<>

NameValueCollection

Dictionary<>

DictionaryEntry

NameValuePair<>

StringCollection

List<String>

StringDictionary

Dictionary<String>

N/A

LinkedList<>

Simple? Nothing funky? Yeah, simple but useful, right?

Share this post: | | | |
Posted: Jul 14 2007, 08:43 AM by very_wel | with no comments
Filed under: ,

Comments

No Comments

Leave a Comment

(required) 

(required) 

(optional)

(required) 
Are you human?:  


Enter the numbers above: