Hi Fred,
because an ArrayList is a reference type not a value type, when you add it
to the hashtable, the hashtable does not store an exact copy of the
ArrayList, it just stores a reference to the original ArrayList, so when you
cleafr the contents out of the array list at the end of your code and then
get the count of the items in the arraylist stored in the hashtable (ie
really the same object) then your result will be zero because you removed all
the items from the list:
i.e. in your code:
Hashtable ht = new Hashtable();
ArrayList atemp = new ArrayList();
ArrayList atemp2;
//remove all the items from the ArrayList and add one item
atemp.Clear();
atemp.Add("5");
atemp.Count -> should equal one
//add a REFERENCE to the arraylist to the hashtable, NOT a copy
//of the arraylist - if you want a copy then you need to Clone the object
//to produce a copy of the object
mp.Add("test",atemp);
if(mp.ContainsKey("test")) // try to retrieve the array in the hashtable,
FOUND
{
//Here you are removing al lthe items form the arraylist, this is the same
//object referenced inside the hashtable
atemp.Clear();
//atemp.Count should equal zero at this point
//retrieve the object reference form the hashtable
atemp2=(ArrayList)mp["test"];
//atemp and atemp2 point to the same instance of an object
//so atemp2 will also have a count of zero.
}
Hope that helps
Mark R Dawson
"Fred" wrote:
I'm trying to build a hashtable and a arraylist as object value
I'm not able to retrieve stored object from the hashtable.
Hashtable mp = new Hashtable(); // THE HASHTABLE
ArrayList atemp = new ArrayList(); // THE ARRAY
StreamWriter sw = new StreamWriter(@"C:\temp\fred.html");
atemp.Clear(); // Create an array with just 1 element "5"
atemp.Add("5");
sw.WriteLine("COUNT:" + atemp.Count ); // give's 1 : OK
mp.Add("test",atemp); // ADD the array to the hashtable
if(mp.ContainsKey("test")) // try to retrieve the array in the hashtable,
FOUND
{
atemp.Clear();
atemp=(ArrayList)mp["test"]; // retrieve arraylist from key "test"
sw.WriteLine("COUNT:"+ atemp.Count ); // give's 0 : ?????
}