Friday, August 10, 2007

Generic Dictionary Class

It's cool.

Here is a scenario. We want to store few Objects or Instances into a collection and then later identify them based on a key. We can use Dictionary class out of System.Collections.Generic.

Dictionary<TKey, TValue>, which is simply a collection of keys and its values.

So, let's say I want to store few objects in 2 different collections, but then retrieve them in particular order. If it was in single collection, it would have been easier to store in the same collection object, but here we need 2 different collections for storing them because, later at the time of retrieval we need to know the type of the object i.e. value we are retrieving.

Here is how we can handle this scenario.

	private Dictionary<int, ClassA> _ClassAObjectCollection;
private Dictionary<int, ClassB> _ClassBObjectCollection;
public void AddClassAObject(int orderNo, ClassA instance)
{
if(instance == null)
throw new ArgumentNullException("instance");
if(_ClassAObjectCollection == null)
_ClassAObjectCollection = new Dictionary();
_ClassAObjectCollection.Add(orderNo, instance);
}

Same way for ClassB.


So, that's just a small and cool example how can we utilize it to store objects and later retrieve these objects based on key from the collection of objects.


No comments:

 
Dotster Domain Registration Special Offer