Jane
Jane

Reputation: 3

Something wrong happens when using for loop to add values into a hashtable

I am not quite sure what exactly goes on when I run the code below to add four values (a, b, c ,d ) into my hash table with C#. But I do know that I get wrong answer. after the loop finished, I get 4 ds stored in my hash table . Help me, Please!

Hashtable cirlTmp = new Hashtable();

CycleLink mycylink = new CycleLink();
int i = 0;
for (i = 0; i < 4; i++)
{
      mycylink.link_id = i;
      mycylink.begine_state = i;//
      mycylink.end_state = 1 + i;
      mycylink.proscDescrp = (process_descrp)i;
      lock (cirlTmp.SyncRoot)
      {
           cirlTmp.Add(i, mycylink);
      }   
 }

what I get in the cirlTemp is

  [3]: link_id=3 begine_state=3 end_state=4 proscDesrp=4;
  [2]: link_id=3 begine_state=3 end_state=4 proscDesrp=4;
  [1]: link_id=3 begine_state=3 end_state=4 proscDesrp=4;
  [0]: link_id=3 begine_state=3 end_state=4 proscDesrp=4;

....... Any hint will be helpful! thanks

Upvotes: 0

Views: 145

Answers (3)

C. Ross
C. Ross

Reputation: 31878

The other answers are correct, you need to move your initialization of mycylink inside your for loop.

Here's why.

You declare a CycleLink. You now start the loop. You configure it. You add it to the hashmap. Everything is fine.

You go to the next element in the loop. You're still pointing to the same CycleLink. You modify the value of the CycleLink and add it to the hashmap. You do it twice more ...

Instead you want to create four CycleLink's and add them each one time.

Upvotes: 1

sll
sll

Reputation: 62544

Basically you adding reference to the same object four times. Each time you updating any property of this object this would be reflected in all hastable entries since all references the same object.

Just move following line inside a for loop:

for (i = 0; i < 4; i++)
{
    CycleLink mycylink = new CycleLink();
    // ...

Upvotes: 0

Bassam Mehanni
Bassam Mehanni

Reputation: 14944

move your CycleLink declaration inside the for loop, you just have a reference to the same object in 4 places in your Hashtable instead of 4 different object

and the value of your object is just the value you set it to in the last run in your loop, that's when i was 3

Hashtable cirlTmp = new Hashtable();

int i = 0;
for (i = 0; i < 4; i++)
{
  CycleLink mycylink = new CycleLink();
  mycylink.link_id = i;
  mycylink.begine_state = i;//
  mycylink.end_state = 1 + i;
  mycylink.proscDescrp = (process_descrp)i;
  lock (cirlTmp.SyncRoot)
  {
    cirlTmp.Add(i, mycylink);
  }   
}

Upvotes: 2

Related Questions