Translate

Sunday, April 3, 2011

c# collection (Introduction to C# collections)

Collections can be thought of as an advanced form of arrays. An array where you can add/remove items, search,sort and perform some other advanced actions.





Most of the collections you will implement in the real world, would be done by using a class in System.Collections Or the System.Collections.Generic Namespace. In this article we will be looking at some interesting, often used classes in the Systems.Collections Namespace. Before we get there, we need to quickly review the purpose of the following interfaces.

Interfaces:


 Interface Name
 Purpose
Implementing this interface in your class, will give you the ability to loop through items in your collection using foreach loop.

 ICollection 
The ICollection interface is the base interface for classes in the System.Collections namespace. This interface provides the ability
  • to obtain the number of items in a collection
  • iterate thru the elements using foreach loop (because this interface inherits from IEnumerable)
  • copy the items of the collection into an array starting an index.
 IList  
Implementing this gives you a collection where the elements can be accessed by an index. For eg myList[0] will return the first item in the collection, myList[1] the second item and so on.

 IDictionary
If you inherit from this interface,  your class can give access to a collection through key/value pair (as opposed to index in IList). For eg myList["7"] will return the item in the collection whose key was set as 7 (not the index).



Classes:



Class Name
Purpose
System.Collections.ArrayList 
Arraylist  will provide you a more advanced form of the simple array. The most useful difference is that the arraylist can be dynamically resized. To resize the arraylist,  you will use the method AddRange(), using which you can add items to the end of the arraylist.
(This class inherits from IEnumerable, ICollection and Ilist.)

If you inherit from this, with very little code you can provide most of the functionalities of a collection that you would  need.
(This class inherits from IEnumerable, ICollection and Ilist.)

If you want to access items by a key rather than by an index, DictionaryBase is the right choice.
(This class inherits from IEnumerable, ICollection and IDictionary.)




No comments:

Post a Comment

Comments will appear once they have been approved by the moderator