tags:

views:

140

answers:

3

I'm working on a C# project that requires me to keep track of various class objects that I have defined...for instance, class1, class2, etc. Each of these classes has an id that is defined as a Guid.

My current method for tracking all of these objects that I create is to store them into a Hashtable. Below is a sample of what I'm doing.

Hashtable c1_db = new Hashtable();
Hashtable c2_db = new Hashtable();

// class 1
Class1 c1_1 = new Class1(..);
Class1 c1_2 = new Class1(..);

// add class1 objects to database
c1_db.Add(c1_1.id, c1_1);
c1_db.Add(c1_2.id, c1_2);

// class 2
Class2 c2   = new Class2(..);
c2_db.Add(c2.id, c2);

So, basically I use each Guid as the Hashtable key for lookup later on when I need to retrieve my objects.

The question that I have is in regards to my implementation here...is this a good way of handling multiple objects? I'm decently new to C#/OOP so I'm sure there are far better ways of doing so...but this seemed like a decently quick/easy/fast way for me to manage internal data.

+3  A: 

In my experience there is nothing inherently wrong with this approach. I've also used it in the past. But you probably want to use a Dictionary<TKey, TValue> because of type-safety in this case. Makes it much easier to handle than a non-generic hashtable.

Joey
+2  A: 

There is nothing wrong with this code. The question is rather what problems it should solve. You can only talk about good / bad solutions if you explain what actually should be achieved.

Stefan Steinegger
+1  A: 

Agreeing with Johannes Rössel, using the hashtable is a fine idea, but would be much nicer if you were able to make it typesafe.

A starting strategy to use would be the following:

Since every object you intend to track contains a GUID, create either a base-class or an interface class that has as its member a GUID as a class member, this will allow you to create your

Dictionary<GUID, iTrackedClass>

Without any issue.

Something else to consider that I use regularly, would be passing the dictionary itself into the constructor for your object and to automcatically add the object to the dictionary as it comes in, to keep your code encapsulated. If you don't want your code to be added to the list, just send in a null and check in the constructor.

greggorob64