Reputation: 77
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.
Upvotes: 0
Views: 66
Reputation: 15247
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>();
}
Upvotes: 3
Reputation: 270790
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();
}
Upvotes: 6