Home > Software engineering >  C# - All objects are getting the same values
C# - All objects are getting the same values

Time:03-02

I am coding a chart. This is my code:

for (int i = 0; i < 2; i  )
{
    Val= new ChartValues<ObservablePoint>(); // added
    Val.Clear(); // added
    lineSeries = new LineSeries
    {
        Title = "Graph "   i,
        Values = Val,
        Stroke = Brushes.Blue,
        Fill = Brushes.Transparent,
        LineSmoothness = 0,
        PointGeometry = null
    };
    
    for (int jj = 0; jj < 2; jj  )
    {
        Val.Add(new ObservablePoint
        {
            X = jj i 1,
            Y = jj i 1
        });
    }
    Col.Add(lineSeries);
}

The problem is that in my Col variable (collection) all series are getting the latest values of the loop, which results are lineSeries are the same. When I use the lineSeries = new LineSeries{}, it should create a new independent object right? Or do I have to erase and create it?

Any help is appreciated.

CodePudding user response:

The issue is that you're reusing the same variable Val to store the actual values. Where is it declared, is it a list? Create a new one each time inside the outer loop and then use it to construct the LineSeries.

for (int i = 0; i < 2; i  )
{
    var Val = new ChartValues<ObservablePoint>();
    for (int jj = 0; jj < 2; jj  )
    {
        Val.Add(new ObservablePoint
        {
            X = jj i 1,
            Y = jj i 1
        });
    }
    var lineSeries = new LineSeries
    {
        Title = "Graph "   i,
        Values = Val,
        Stroke = Brushes.Blue,
        Fill = Brushes.Transparent,
        LineSmoothness = 0,
        PointGeometry = null
    };
    
    Col.Add(lineSeries);
}

CodePudding user response:

the problem is in line series, you use the same variable, and you are adding the same variable. It it changing each time, and in the end have the last data

lineSeries = new LineSeries
{
       ......
};

should be

var lineSeries = new LineSeries
{
       ......
};

  •  Tags:  
  • c#
  • Related