Link to home
Start Free TrialLog in
Avatar of freename
freenameFlag for United States of America

asked on

Get value from hashtable when value is an array

I've got a hashtable where the value for a key is a 2 element string array. However, when I attempt to retrieve the value array, I receive the error "Cannot apply indexing with [] to an expression of type 'object' ".  Attached is a crude code snippet to illustrate my attempt.
Hashtable ht = new Hashtable();
            string[] a1 = {"A0", "A1"};
            string[] a2 = {"B0", "B1"};
            ht.Add(0, a1);
            ht.Add(1, a2);
            foreach (object sk in ht.Keys) 
                object A0 = ht[sk];
                string first = A0[0];

Open in new window

Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Link to home
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of freename


Oh man, so simple. I didn't even think of that.
Hi freename;

Here is the same thing but using Generics class Dictionary. This version is type safe and does not need casting it results.

            Dictionary<int, String[]> dic = new Dictionary<int, string[]>();
            string[] a1 = { "A0", "A1" };
            string[] a2 = { "B0", "B1" };
            dic.Add(0, a1);
            dic.Add(1, a2);
            foreach (int idx in dic.Keys)
                String[] A0 = dic[idx];
                Console.WriteLine(A0[0] + "   " + A0[1]);