Monday, August 4, 2008

Creating a StringCollection Array in C#.

This explanation was tried in C# 2.0. Basically we all know that StringCollection class allows you to store multiple strings. But unfortunately it doesn't have the possibility of using it as an Array type. But interestingly it allows you to define something like:
StringCollection[] coll = new StringCollection[2];
You get no compile errors,but you cannot access it.It will give a Runtime error, which still I don't know why. I was in need of having a set of related StringCollections stored in an array. So after some discussion and analysis with a friend, we both came up with a solution to achieve what I wanted. I was able to create, and access my StringCollection Array like this:

Initially import the the following mnaespaces:
using System.Collections.Generic;
using System.Collections.Specialized;

Then some where in a button click event (or just anywhere you prefer):

//Create two string arrays

String[] nameArr = new String[] {"Mafaz","David" };
String[] countryArr = new String[] {"Srilanka","India" };

//The primary StringCollections i'm storing
//the array values to

StringCollection nameColl = new StringCollection();
StringCollection countryColl = new StringCollection();

//Adding the arrays to the relevant StringCollections

nameColl.AddRange(nameArr);
countryColl.AddRange(countryArr);

//declare an ArrayList with the number of StringCollections
//which we want to atore as Arrays
//Basically this will serve as a StringCollection Array.
//In this case we have two string collections

ArrayList al = new ArrayList(2);

//Add the StringCollections as Elements

al.Add(nameColl);
al.Add(countryColl);

//Two view the elements again

StringCollection coll2 = new StringCollection();

//You have to cast it to StringCollection type from the
//arraylist

coll2 =(StringCollection) al[0];
Console.WriteLine("Names :"+ coll2[0] + coll2[1]);

coll2 =(StringCollection) al[1];
Console.WriteLine("Countries :"+ coll2[0] + coll2[1]);

You can use a loop also to iterate through many StringCollection array elements. So that's it, That's how you create a StringCollection Array... :-)