views:

260

answers:

4

How could I get the string value from a hashtable without calling toString() methode?

example: my class:

public class myHashT : Hashtable
{
 public myHashT () { }
 ...
 public override object this[object key]
      {
         get
         {
            return base[key].ToString(); <--this doesn't work!
         }
         set
         {
            base[key] = value;
         }
      } 
}

In an other class:

myHashT hT;
string test = hT["someKey"];

it works with hT["someKey"].toString(); but I need it without calling ToString() and without casting to (string).

A: 

If i understand correctly, value in the hashtable is a string?

If so, you need to cast the object as a String.

string test = (string)hT["someKey"];
yankee2905
A: 

I think you need to cast hT["someKey"] to a string.

Matt Ball
+1  A: 

Can you just cast?

(string)hT["someKey"]

Note that if this is 2.0 or above, a generic Dictionary<string,string> would be far simpler... and in 1.1 StringDictionary would do the job (although IIRC you need to watch for case-insensitivity in the key).

Marc Gravell
what about the reading speed?
Jooj
It'll be about the same; O(1)
Marc Gravell
A: 

Hi!

You could use System.Collections.Generic.HashSet. Alternately use composition instead of inheritance ie. have hashtable be your private field and write your own indexer that does ToString().

public class myHashT
{
public myHashT () { }
...

private Hashtable _ht;

public string this[object key]
{
  get
  {
     return _ht[key].ToString();
  }
  set
  {
     _ht[key] = value;
  }
}

}

Goran