0

I have one class with 2 lists as it's data member. I want to include these data members as a different class' objects.

I am getting this error:

"Object reference not set to an instance of an object."

Kindly advise what should be the proper approach.

class dataPoints
{
    public List<double> dataValues;
    public List<DateTime> timeStamps;

    public dataPoints()
    {
      this.timeStamps = new List<DateTime>();
      this.dataValues = new List<double>();
    }
}


//I want an object of dataPoints in this below classs
class wellGraph
{
    int seriesAdded;
    dataPoints[] graphDataPoints;

    public wellGraph(int Entries)
    {
        this.seriesAdded = 0;
        this.graphDataPoints = new dataPoints[Entries];

        for(int i=0;i<Entries;i++)
        {
            graphDataPoints[i].timeStamps = new List<DateTime>();
            graphDataPoints[i].dataValues = new List<double>();
        }

    }
}

With the constructor removed in dataPoints class, the same error persists.

chiro3110
  • 77
  • 7
  • 5
    You're never initializing the elements of the array. You need `graphDataPoints[i] = new dataPoints();` before you set the field values. I'd also strongly recommend that: a) you follow .NET naming conventions; b) you use properties rather than public fields. – Jon Skeet Jan 15 '19 at 09:15
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – A Friend Jan 15 '19 at 09:21
  • Possible duplicate of [Instantiate an array of objects, in simpliest way?](https://stackoverflow.com/questions/9333232/instantiate-an-array-of-objects-in-simpliest-way) – mjwills Jan 15 '19 at 09:27

2 Answers2

6

You have created an array of dataPoints (which should be called DataPoints according to naming standards of C#), but you have not created the dataPoints objects themselves. The elements in the array are all null, hence the null reference exception.

Therefore, inside the for loop, you should create the dataPoints objects using new dataPoints():

for(int i=0;i<Entries;i++)
{
    graphDataPoints[i] = new dataPoints();
}
Sweeper
  • 213,210
  • 22
  • 193
  • 313
3

You instancied the array, but not the elements inside.

for(int i = 0; i < Entries; i++)
{
    graphDataPoints[i] = new dataPoints();
    // I removed the lines below because they are already initialized in the constructor
    // graphDataPoints[i].timeStamps = new List<DateTime>();
    // graphDataPoints[i].dataValues = new List<double>();
}
Cid
  • 14,968
  • 4
  • 30
  • 45