I created a program with multiple classes and multiple lists in each class.
In the following you’ll find a code example:
RsiClass rsi = new RsiClass();
RSI = await rsi.RsiDrawGraph(valueList);
The function rsi.RsiDrawGraph() (in my child class) changes the values in the list:
public async Task<List<RsiModel>> RsiDrawGraph(List<ChartDataModel> allValue)
{
List<RsiModel> returnValues = new List<RsiModel>();
for (int i= allValue.Count - 1; i>=0; i--)
{
returnValues.Add(new RsiModel { LowerBorder = 30, UpperBorder = 70, rsi = await Rsi(allValue), Time = allValue[i].Time, x=allValue[i].x });
allValue.RemoveAt(i);
}
return returnValues;
}
Finally, the function returns the expected results but the values in my other "valueList" also changed too. In detail, it seems that the removeAt() command effected my other valueList in the main class, because the valueList is empty after the operation.
Why does it happened and how can I prevent, that the childclass is effecting my list in the main class?
>Solution :
Let’s assume the caller of RsiDrawGraph does not expect you to modify allValue you can do something like this:
public async Task<List<RsiModel>> RsiDrawGraph(IEnumerable<ChartDataModel> allValue)
{
List<ChartDataModel> chartData = new List<ChartDataModel>(allValue);
List<RsiModel> returnValues = new List<RsiModel>();
for (int i = chartData.Count - 1; i > = 0; i--)
{
returnValues.Add(new RsiModel { LowerBorder = 30, UpperBorder = 70, rsi = await Rsi(chartData), Time = chartData[i].Time, x=chartData[i].x });
chartData.RemoveAt(i);
}
return returnValues;
}
This way, you’re modifying a copy of allValue that is local to the method so you avoid unexpected side effects.