Amit
Amit

Reputation: 22086

NullReferenceException even when after "new MyType[]"?

I am using MSChart and I am creating array like this

DataPoint[] datapoint = new DataPoint[10];
datapoint[0].SetValueY(86);

but it is giving error

NullReferenceException: Object reference not set to an instance of an object.

Why is it giving error?

Upvotes: 1

Views: 346

Answers (4)

Frédéric Hamidi
Frédéric Hamidi

Reputation: 263047

Your array initially contains 10 null references. You have to populate it with actual object references before using it. Try something like:

DataPoint[] datapoint = new DataPoint[10];
for (int i = 0; i < datapoint.Length; ++i) {
    datapoint[i] = new DataPoint();
}

datapoint[0].SetValueY(86);

Upvotes: 3

Greg
Greg

Reputation: 23483

You need to initialize the DataPoints in the array.

DataPoint[] datapoint = new DataPoint[10];
datapoint[0] = new DataPoint();
datapoint[0].SetValueY(86);

Upvotes: 1

JaredPar
JaredPar

Reputation: 755161

I'm not familiar with DataPoint but it appears that it is a class. Hence the expression new DataPoint[10] creates an array of 10 values all of which are initialized to null. You'll need to initialize the elements before using them. For example

datapoint[0] = new DataPoint();
datapoint[0].SetValueY(86);

Upvotes: 2

Kyle Trauberman
Kyle Trauberman

Reputation: 25694

Because the object at index 0 in the datapoint array is null.

Add this line before the SetValueY method call:

datapoint[0] = new DataPoint();

You'll need to do this for each index in the array (0 - 9) or populate the array with DataPoint objects some other way (using LINQ, for example)

Upvotes: 3

Related Questions