I'm trying to make a list of class as history.
So list of a class was declared like this.
private List<SearchHistoryItem> SearchHistoryList;
SearchHistoryItem is a class that have two property.
public DataTable SearchResultDataTable;
public SearchCondition SearchCondition; // this is another class.
Whenever this method is called, I make temporary 'SearchHistoryItem', copy from current instance and add to the list.
public void GetMainDataAsConditionMethod()
{
SearchHistoryItem tmpItem = new SearchHistoryItem();
tmpItem.SearchCondition = CurrentSearchCondition;
tmpItem.SearchResultDataTable = MainChartDataTable;
SearchHistoryList.Add(tmpItem);
}
I think there is no reason to copy datas by reference. But when this code is running, every items in the List 'SearchHistoryList' have same values of CurrentSearchCondition and MainChartDataTable. I checked How can I solve this to be copied by value?
When you assign an object (such as a List) to a variable, you assign a reference. When you do anything to the object on one reference, all references will show the change, because they are just references to the same object.
What you want to do is copying the list before you pass it on, such as
tmpItem.SearchResultDataTable = new List<...>();
tmpItem.SearchResultDataTable.AddRange(MainChartDataTable);
Note: This only creates a shallow copy, not a deep copy. If you want a deep copy, would have to clone each object in the list individually.