0

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

3 Answers 3

2

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);
  }   
}
Sign up to request clarification or add additional context in comments.

1 Comment

@Jane No problem, don't forget to mark the answer as correct for future users
1

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.

Comments

0

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();
    // ...

1 Comment

Thanks Sll, Yes, it should be.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.