Home > Enterprise >  C# - An object is deleted from an array that holds a copy of the original
C# - An object is deleted from an array that holds a copy of the original

Time:06-29

I hold an array in the following structure List[] pageStore = new List[2]; Each cell of the array will contain a list of Page objects.

I wrote a function that ran in a loop and in each iteration creates a new list of Page. I keep the list created in the above List. Before each iteration I delete the contents of pages and the deletion is also done on the array itself.

How can this be prevented so that the array will keep the records I saved?

my code :

List<Page>[] pageStore = new List<Page>[2];
public void LoadExcel(Dictionary<string,string[]> FilePaths){
  List<Page> pages = new List<Page>();
  int pageStoreIndex = 0;
  foreach (KeyValuePair<string, string[]> entry in 
  FilePaths) {
   pages.Clear();
   for (int i = 0; i < entry.Value.Length; i  ) {
     if (i == 0)
     pages = fileManager.ParseExcelToObjects(excelDataSet, 
ProjectTypeSelected.Name,entry.Key.Equals(Enum.Enums.ConnectorSide.COMBINED.ToString()) ? false : true);
    ...
    ...
   }
   if (pages.Count > 0) 
     pageStore[pageStoreIndex  ] = pages;
  }
}

page.Clear() cleared pageStore also.

CodePudding user response:

You need to create a copy of the list.

pageStore[pageStoreIndex  ] = new List<Page>(pages);

CodePudding user response:

Like most .Net objects, List<T> is a reference type. Your line:

pageStore[pageStoreIndex  ] = pages;

is just storing a reference to the single pages instance. It's not copying the values across. Every array entry is pointing at the same list.

As other answers have said, you need to create a new list each time if you want to keep separate lists:

List<Page>[] pageStore = new List<Page>[2];

public void LoadExcel(Dictionary<string,string[]> FilePaths)
{
  int pageStoreIndex = 0;

  foreach (KeyValuePair<string, string[]> entry in FilePaths) 
  {
    //create a new list for each loop iteration
    var pages = new List<Page>();

    for (int i = 0; i < entry.Value.Length; i  ) 
    {
      //ps the following lines don't make sense. You've created a new List above, 
      //but ParseExcelToObjects() ignores it and returns its own list.
      //So either your new List<Page>() is pointless, or this call is different in the real code.
      if (i == 0)
        pages = fileManager.ParseExcelToObjects(excelDataSet, ProjectTypeSelected.Name,entry.Key.EqualsEnum.Enums.ConnectorSide.COMBINED.ToString()) ? false : true);
      ...
      ...
    }

    if (pages.Count > 0) 
      pageStore[pageStoreIndex  ] = pages;
  }
}

CodePudding user response:

You've assigned the value in pageStore to be the pages object. You'll need to create a new object using List<T>'s copy constructor:

if (pages.Count > 0) 
     pageStore[pageStoreIndex  ] = new List<Page>(pages);
  • Related