8


I have a code like this.

Hashtable ht = new HashTable();
ht["LSN"] = new string[5]{"MATH","PHIS","CHEM","GEOM","BIO"};
ht["WEEK"] = new string[7]{"MON","TUE","WED","THU","FRI","SAT","SUN"};
ht["GRP"] = new string[5]{"10A","10B","10C","10D","10E"};

now i want to get values from this ht like below.

string s = ht["LSN"][0];

but it gives error. So how can i solve this problem.

0

7 Answers 7

11

I think you want to use a generic typed Dictionary rather than a Hashtable:

Dictionary<String, String[]> ht = new Dictionary<string, string[]>();

ht["LSN"] = new string[5] { "MATH", "PHIS", "CHEM", "GEOM", "BIO" };
ht["WEEK"] = new string[7] { "MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN" };
ht["GRP"] = new string[5] { "10A", "10B", "10C", "10D", "10E" };

string s = ht["LSN"][0];

This should compile fine.

Otherwise you need to perform a cast such as:

string s = ( ht[ "LSN" ] as string[] )[ 0 ];
Sign up to request clarification or add additional context in comments.

1 Comment

+1 for the dictionary. This is the better fitting type for these kind of problems.
2

Hashtable stores untyped objects: you'd need to re-cast the value you read back into a string array, e.g.

string s = ((string[])ht["LSN"])[0];

or

string s = (ht["LSN"] as string[])[0];

However you're better off using something typed, e.g. a Dictionary<> - then it'll just work:

Dictionary<string, string[]> ht = new Dictionary<string, string[]>();
...
string s = ht["LSN"][0];

Comments

2

Your hashtable is of type object, so when you try to access the array, you will get an error since object does not support the array accessor syntax you are using. if you used a dictionary, as explained in other answers, you could use generics to define that you are using string arrays rathe than objects, which will work as you wish.

alternatively, you can cast your variables like this:

string[] temp = (string[])ht["LSN"];

this will give you the access to temp that you desire.

Comments

1

your ht["LSN"][0] will return you a string array. so you have to add another indexer to get proper value.

((string[])ht["LSN"][0])[0]

Comments

1

Since Hashtable contents are exposed as object you would need to cast:

string s = (ht["LSN"] as string[])[0];

But you would probably be better off using a strongly-typed container as suggested by Nick.

Comments

1

The indexer of the HashTable class always returns an instance of object. You'll have to cast that object to an array of strings:

string s = ((string[]) ht["LSN"])[0];

That said, consider using the generic Dictionary<TKey, TValue> class instead.

Comments

1
string[] aStrings = (string[])ht["LSN"];
string s = aStrings[0];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.