I am having really a weird issue with my current project. I have sample classes that will hold some data as a collection (List<SampleData>
). and I have used another stack collection (Stack<SampleData>
) for logging the data that was added to the first list. after modifying the first list's first index data, the stack data was modified without my knowledge.
public class ActionLog
{
private Stack<SampleData> UndoStack;
public ActionLog()
{
UndoStack = new();
}
public void Log(SampleData Data)
{
UndoStack.Push(Data);
foreach (var item in UndoStack)
System.Console.WriteLine($"{item.Name}");
}
}
public class ActivityControl
{
public ActionLog Logger { get; set; } = new ActionLog();
public List<SampleData> Datas { get; set; } = new List<SampleData>();
public void Initiallize(List<SampleData> datas)
{
Datas.AddRange(datas);
Logger.Log(datas[0]);
}
}
internal class Program
{
static ActivityControl contorl = new ActivityControl();
static void Main(string[] args)
{
List<SampleData> list = new List<SampleData>();
SampleData data = new SampleData()
{
Name = "Data 1"
};
SampleData data2 = new SampleData()
{
Name = "Data 2"
};
list.Add(data);
list.Add(data2);
contorl.Initiallize(list);
contorl.Datas[0].Name = "Data 11";
contorl.Logger.Log(new SampleData() { Name = "Fake Data" });
Console.ReadKey();
}
}
The out put for the above code should be : Data 1 , Fake Data, Data 1 but i am seeing Data 1, Fake Data, Data 11