Using VB collections in C#
I talked to Patrick about the problem he had with hashtables and how good he thinks the VB.Net collections are. He wanted to add objects to a list and retrieve them in the order in which they were entered. Hash tables are organized using the hash code of the key. A SortedList could work, but then you need to be aware of how your keys are defined. A Queue might work in this scenario, but why not use the VB.Net Collection object in C#.
I have used Vb.Net objects before in C# applications, and they work fine. I posted about this before, when explaining how to use VB.Net checks like IsNumeric and IsDate in C# applications. So let me show you how you can use VB.Net collections in C#.
- First, add a reference to Microsoft.VisualBasic to your project. You can find the Microsoft.VisualBasic in the list on the .Net tab when you open the Add reference dialog.
- At the top of your code, where the using directives are, you add the following line of code:
using Microsoft.VisualBasic;
- Now you can use the Collections object.
The following example can be used to prove that the VB.Net Collections works:
private void test()
{ Collection col = new Collection();
col.Add("first", "key1", null, null); col.Add("second", "key2", null, null); col.Add("third" , "key3", null, null);
foreach (string test in col)
{ Console.WriteLine(test);
}
}
The code produces the following result:
first
second
third
I tried this in both VS2003 and VS2005. Works like a charm. Who say's VB.Net and C# don't get along?