-3

I have built a simple code as shown below. While debugging, I am getting an error about "NullReference Handled Exception" at the code line:

X.DataPoints.Add(dp);

Here is the code snippet. Please advice on what am I missing?

  public class RankPlot
        {
            public List<RankPlotDataPoint> DataPoints { get; set; }
        }

        public class RankPlotDataPoint
        {
            public double RankVal { get; set; }
            public double ProbVal { get; set; }
        }

        ObservableCollection<RankPlot> EURresults = new ObservableCollection<RankPlot>();
        public ObservableCollection<RankPlot> EURResults
        {
            get { return EURresults; }
            set
            {
                EURresults = value;
                base.OnPropertyChanged("StringList");
            }
        }
        public void evaluate()
        {
            RankPlot X = new RankPlot();

            for (double i = 0; i<5; i++)
            {
                RankPlotDataPoint dp = new RankPlotDataPoint();
                dp.RankVal =i+1; // Y axis
                dp.ProbVal = i; // X axis

              X.DataPoints.Add(dp);

            }
            EURResults.Add(X);
        }
Cartman23
  • 53
  • 1
  • 8

4 Answers4

1

You are getting Null Exception Because you need to initialize the List<RankPlotDataPoint> DataPoints. So Instead of Initialize DataPoints every time you create an instance of RankPlot, you should initialize like below:

Change your Below Statement:

public class RankPlot
{
    public List<RankPlotDataPoint> DataPoints { get; set; }
}

To

public class RankPlot
{
    public List<RankPlotDataPoint> DataPoints { get; set; } = new List<RankPlotDataPoint>();
}
Waqar Ahmed
  • 1,387
  • 2
  • 12
  • 34
1

in evaluate() method instead of

RankPlot X = new RankPlot();

write

RankPlot X = new RankPlot{DataPoints  = new List<RankPlotDataPoint>()};

It'll initialize the list.

ATP
  • 571
  • 1
  • 3
  • 16
0

X.DataPoints = new List<RankPlotDataPoint>(); you never initialize the list before you add items to the list.

Xela
  • 2,300
  • 1
  • 16
  • 30
  • @JK My answer answers his question. If you don't think it does you must seriously be a water head. – Xela Oct 20 '15 at 04:15
0

You are trying to add a value to a List<RankPlotData> that doesn't exist. With your property in the RankPlot class, you need to declare a new List of RankPlotData in your RankPlot class, and initialize it with .. new List<RankPlotData>(). Then, you should return that from your property get accessor.

brads3290
  • 1,303
  • 1
  • 11
  • 18