views:

56

answers:

2

I have class Foo. Foo has a property of public string x.

I would like to instantiate Foo a few times as ONE and TWO, and add those instances to Hashtable Bar with keys 1 and 2 respectively. How do I obtain string x for the particular instance.

I've tried something to the like of: Bar[1].x, but the property x is not recognized.

What am I doing wrong?

+6  A: 

You should be using Dictionary<int, Foo> instead of Hashtable. Hashtable is an obsolete class for the days we didn't have generics. It stores key and values as object type. Dictionary<TKey,TValue>, on the other hand, is a strongly typed generic collection.

If you want to use Hashtable for some reason (e.g. C# 1.0), you'll have to cast the object:

 ((Foo)Bar[1]).x
Mehrdad Afshari
A: 

you may need to cast once oyu retrieve from the Hashtable. Try: string s = (myHashtable[myKey] as Foo).x;

Arg! Just saw Mehrdad Afshari's answer, which correctly points this out

FOR
Re your usage of "as", see: http://stackoverflow.com/questions/2139798/why-is-the-c-as-operator-so-popular/2139818#2139818
Mehrdad Afshari
As far as using "as", that was just a quick line.. I'll leave the decision of using "as" or the direct cast to the reader as an exercise, but thank Mehrdad for the valuable link
FOR