Add a Value to an ArrayList

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I would like to add a value to my ArrayList. When I add u to orderedpair
below I get the same data for each. I know why, I am Add ing u. I want to
add the VALUE of u at the point in the for loop, NOT q.

Does anyone know how to do this?

for (int q = 0; q < orderedlistx.Count - 1; q++)
{


u.Start = (int)orderedlistx[q];
u.End = (int)(orderedlistx[q+1])-1;


orderedpair.Add(u);
}
 
Andy in S. Jersey said:
I would like to add a value to my ArrayList. When I add u to orderedpair
below I get the same data for each. I know why, I am Add ing u. I want
to
add the VALUE of u at the point in the for loop, NOT q.

Does anyone know how to do this?

Perhaps your question would be more clear if you could tell us what you
expect to happen, and what actually happens.

As near as I can tell, you *are* adding "the value of u at the point in the
for loop".

A couple of thoughts:

* If you want to add "u" to a specific position within the "orderedpair"
list, you can use the Insert method instead of Add

* If "u" is not a value type, then what you're adding to the array is a
reference "u", where "u" refers to some instance of some object. If you
don't create a new instance and assign its reference to "u" each time
through the loop, then you're going to wind up with an array that has the
reference to "u" duplicated in each entry, and of course using that
reference will result in getting the same data regardless of which entry in
the array you look at.

Whether either of the above are applicable to your question I don't know.
The question is too vague. If those thoughts don't help, try restating the
question as I suggested above.

Pete
 
Andy in S. Jersey said:
I would like to add a value to my ArrayList. When I add u to orderedpair
below I get the same data for each. I know why, I am Add ing u. I want to
add the VALUE of u at the point in the for loop, NOT q.

Does anyone know how to do this?

for (int q = 0; q < orderedlistx.Count - 1; q++)
{


u.Start = (int)orderedlistx[q];
u.End = (int)(orderedlistx[q+1])-1;


orderedpair.Add(u);
}

You are inserting a reference to the same object, u, over and over. You need
a u = new SomeType() before you set u.Start.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top