Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding items to a LIST<> of objects results in duplicate Objects when using a NEW in a Loop

Tags:

c#

loops

list

List<BillOfLading> bolList = new List<BillOfLading>();

protected void Button1_Click(object sender, EventArgs e)
{
    BillOfLading newBol = new BillOfLading("AXSY1414114");
    bolList.Add(newBol);

    newBol.BillOfLadingNumber = "CRXY99991231";
    bolList.Add(newBol);
}

I was expecting that bolList would container two different objects or values, but it appears that this simple code doesn't work. Any ideas?

Resulting Immediates:

bolList

Count = 2
    [0]: {kTracker.BillOfLading}
    [1]: {kTracker.BillOfLading}
bolList[0]
{kTracker.BillOfLading}
    _billOfLadingNumber: "CRXY99991231"
    BillOfLadingNumber: "CRXY99991231"
bolList[1]
{kTracker.BillOfLading}
    _billOfLadingNumber: "CRXY99991231"
    BillOfLadingNumber: "CRXY99991231"
like image 575
Havingfun Avatar asked Feb 12 '11 15:02

Havingfun


People also ask

Why does adding a new value to List <> overwrite previous values in the list <>?

Essentially, you're setting a Tag's name to the first value in tagList and adding it to the collection, then you're changing that same Tag's name to the second value in tagList and adding it again to the collection. Your collection of Tags contains several references to the same Tag object!

Can we create a list inside another list?

One list can be used within other lists. Such lists are called Nested Lists.


1 Answers

You've only created one object, and added it twice. The fact that you modified that object between the first and second add is irrelevant; the list contains a reference to the object you added, so later changes to it will apply.

You need to replace newBol.BillOfLadingNumber = ".."; with newBol = new BillOfLading("..");

like image 58
Flynn1179 Avatar answered Nov 15 '22 06:11

Flynn1179