Reputation: 9003
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?
Upvotes: 1
Views: 268
Reputation: 4368
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
Upvotes: 0
Reputation: 421998
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
Upvotes: 6