not sure what is going on here. My data items I store in the first dictionary entry get overwritten when I go to update data to the second entry. The dictionary's first entry is acting like it is using a reference to the original object so when i change it all instances in the dictionary change. the first set of data is 1,2,3 and stored in partitionInfo[0]. when i got to store the next set of data, 4,5,6 partitionInfo[1] updates but parttionInfo[0] updates those values as well. so i end up with my two dictionary entries have the same set of data. however the strings stay unique. representation code of what i am seeing
private void button1_Click(object sender, EventArgs e)
{
Datum dataItems = new Datum();
Partition partitionItem = new Partition();
LRU lruItem = new LRU();
dataItems.minData = "1";
dataItems.maxData = "2";
dataItems.avgData = "3";
partitionItem.partitionInfo.Add("Entry1", dataItems);
dataItems.minData = "4";
dataItems.maxData = "5";
dataItems.avgData = "6";
partitionItem.partitionInfo.Add("Entry2", dataItems);
lruItem.lruInfo.Add("Parent", partitionItem);
}
public class LRU
{
public Dictionary<string, Partition> lruInfo = new Dictionary<string, Partition>();
}
public class Partition
{
public Dictionary<string, Datum> partitionInfo = new Dictionary<string, Datum>();
}
public class Datum
{
public string minData;
public string maxData;
public string avgData;
}
CodePudding user response:
You are overwriting your values beginning with the line dataItems.minData = "4";
Just because you've stored the value in Entry1
it doesn't "lock it away" as I suspect you think.
You original comment:
The dictionary's first entry is acting like it is using a reference to the original object so when I change it all instances in the dictionary change
You were close to grasping the error in your code...
See the fixed code:
Partition partitionItem = new Partition();
Datum dataItems = new Datum();
// **** It's better to declare your variables just
// before you use them to make it clearer ****
dataItems.minData = "1";
dataItems.maxData = "2";
dataItems.avgData = "3";
partitionItem.partitionInfo.Add("Entry1", dataItems);
dataItems = new Datum(); // **** ADDED LINE ****
// We now have a new block of memory containing a `Datum`
// the one above is left untouched
dataItems.minData = "4";
dataItems.maxData = "5";
dataItems.avgData = "6";
partitionItem.partitionInfo.Add("Entry2", dataItems);
LRU lruItem = new LRU(); **** Moved, as before ****
lruItem.lruInfo.Add("Parent", partitionItem);