Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

RemoveAt() should not delete values in multiple C#-lists

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading