KnowDotNet Visual Organizer

Creating a VB.NET or VB6 Type Collection in C# Using a HashTable

by Les Smith
Print this Article Discuss in Forums

VB6 and VB.NET collections were easy to use and allowed you to reference an object in the collection either by index or by key.  The downside of a VB.NET collection is that it was not strongly typed; therefore, you could put anything into a collection, even objects of differentd types, which seems fairly tricky at best.  

There is no direct correlation to a VB.NET or VB6 collection in C#.  However, you have several options.  First, you can create a strongly typed collection, which is probably the best solution, unless you need to reference objects within the collection by Key.  Another option is that you can use a HashTable as a collection and reference the objets by Key.  The downside to this is that you cannot reference an object in a HashTable by index; you must use a key.  So you are faced with a dilemma when you are moving from VB to C# and have been using collections in VB.  

You have to decide whether you need to access the objects by index or by key, and it appears that there is not an easy way to do both.

By the way, if you are not new to C#, you may not want to take time to read this article.  This is just something I discovered along the journey while converting a large project from VB to C#.

If you want to get at the objects by key, you use a hash table as follows.  First, create the collection

    private Hashtable myCollection = new Hashtable();

Next, fill the collection with some code like the following.

        int tempFor1 = dt.Rows.Count;
        
foreach (DataRow dr in dt.Rows)
        {
          job =
new JobObject();
          job.Department = dr[
"department"];
          job.WorkType = dr[
"work_type"];
          job.JobNumber = dr[
"job_number"];
          myCollection.Add(job.JobNumber,job);
        }

At the bottom of the loop, I have added the object to the collection.  The Add method of the HashTable accepts two parameters.  First, the key, which is the JobNumber, and second, the object itself.

Now when you want to reference the object, using a JobNumber, use this code.

   JobStruct js = (JobStrut) colJobs[123456];  

Thus, you have a collection, just like the VB collection, in which you can reference an object using a key.

If you want a simple collection, that is not strongly typed, that will allow you to get at the object by index, then an Array or ArrayList (C# gurus cringe I'm sure).  In VS2005, you will be able to use generics instead of this approach and I believe that to be strongly typed, but then again, the key is a problem.


Writing Add-Ins for Visual Studio .NET
Writing Add-ins for Visual Studio .NET
by Les Smith
Apress Publishing