Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List.Add(x). Is x a REFERENCE or a VALUE?

Tags:

c#

Regarding this data and (pseudo) code:

List<myClass> Periods = new List<myClass>();

// contents of Periods is:
Periods[0] = "000";
Periods[1] = "111";
Periods[2] = "222";
Periods[3] = "REST"; // REST PERIOD
Periods[4] = "444";
Periods[5] = "REST"; // REST PERIOD
Periods[6] = "666";
Periods[7] = "777";
Periods[8] = "888";

The following code iterates through the list, and pulls out multiple list elements as they occur between REST periods into individual lists, and adds these lists to a "list of lists". There may be one or more List Entries between rest periods.

List<List<Period>> DutyDayPeriods = new List<List<Period>>();
List<Period> thisList = new List<Period>();

for (int i = 0; i < Periods.Count; i++ ) {    
    thisList.Add(Periods[i]);

    if (Periods[i].Rest == "REST") {   
        DutyDayPeriods.Add(thisList);
        thisList.Clear();   
    }    
}

At the bottom of the for loop, DutyDayPeriods<> contains 1-n identical copies of "thisList". Essentially the last set of list items between the last rest period and the end of the list:

So, I am expecting the following:

DutyDayPeriods[0]
    Period 000
    Period 111
    Period 222
DutyDayPeriods[1]
    Period 444
DutyDayPeriods[2]
    Period 666
    Period 777
    Period 888

But I'm actually getting:

DutyDayPeriods[0]
    Period 666
    Period 777
    Period 888
DutyDayPeriods[1]
    Period 666
    Period 777
    Period 888
DutyDayPeriods[2]
    Period 666
    Period 777
    Period 888

thisList is behaving like a reference, not a value.

Every time thisList changes, it seems to change retroactively to items that have already been added to DutyDayPeriods.

Is this the case? And if so, how do I accomplish what I am trying to do?

Thanks.

EDIT:

I modified the following to prevent the rest periods themselves from being included. Just in case one of you notices that. ;-)

if (Periods[i].Rest != "REST") {
    thisList.Add(Periods[i]);
}
else {
    DutyDayFlights.Add(thisList);
    thisList = new List<Period>();  
}
like image 609
KWallace Avatar asked Mar 05 '23 15:03

KWallace


1 Answers

Yes, a List<T> is always a reference.

You just need to replace .Clear() with creating a new list.

DutyDayPeriods.Add(thisList);
//thisList.Clear();   
thisList = new List<Period>();
like image 118
Henk Holterman Avatar answered Mar 16 '23 02:03

Henk Holterman