We all have come across a situation where we need to store a collection of a specific type.
Let's say for example we have a class called Customer and we need to have a collection of customers.
Simple way of doing that may be to use ArrayList and add customer class to it. But we have to pay a heavy price for using an ArrayList.
For those of you who don't know the pitfalls of using ArrayList, let me briefly list it out.
- The default initial capacity of an ArrayList is 16, even if you add only 2 items to the ArrayList object it will still occupy memory area of 16 elements.
- Assume you have added 17th element in your ArrayList object then your object will grow to 32 capacity, that's real waste of memory.
- ArrayList stores everything as object and so any value type you store goes through an overhead of boxing and unboxing. Boxing and Unboxing is the most performance intensive operation in .Net as it has to convert a value type to a reference type and the vice versa.
- There is no type safety as you can store any type in an ArrayList object.
Now where do the Generics come in picture.......??
Well they are the saviors in this .Net world, don't believe me then look how simple and smart generics are.
Now we have a class called Customer and I want a collection of Customer to store n numbers of customers.
//Sample code
objCustomerColl = new List();
Essentially what we are doing in the above given line of code is we are using the List class which is part of the System.Collections.Generic namespace.
The declaration is pretty simple we are telling the compiler that create a list of Customer class.
With this simple piece of code we have our CustomerCollection ready for use.
Now we can add, remove and perform many different operations on it.
//Sample code
objCustomerColl.Add(new Customer());
Points to be noted....
This generic list is type safe.
- If you use a value type to create a generic list it doesn't require boxing/unboxing.
- All the incrementing/decrementing of the list is done under the hood.
Few more examples of Generic list....just to give you an idea of how powerfull are generics.
List IntCollection = new List();
List StringCollection = new List();