Object reference exception error for using Hashtable, why?

A

A. Burch

I posted early about Hashtable use and the shallow/deep copy and storing a
reference answered that question.

I've got a larger implementation of this, but am not sure why I'm getting
this error. Object reference not set to an instance of an object. I don't
know what I'm missing. What needs to be fixed for this implementation to
work?

using System;
using System.Collections;
public class SamplesHashtable
{
static Hashtable HT = new Hashtable();
public static Q[] qrec = new Q[2];
public static void Main()
{
qrec[0].symbol = "HI";
qrec[0].price = 4.0;
HT.Add("First", qrec[0]);
qrec[1].symbol = "BYE";
qrec[1].price = 5.0;
HT.Add("Second", qrec[1]);
qrec[0] = (Q)HT["First"];
qrec[0].price = qrec[0].price - 1.0;
}
public class Q
{
public string symbol;
public double price;
}
}
 
R

Richard A. Lowe

Q is a class and therefore a reference type. When you create an array of
reference types you get an array with all the members set to null. You have
to populate each member (calling Initialize() on the array will NOT work for
reference types).

So Q[0]==null until you go Q[0]=new Q();

Richard
 
J

John Wood

qrec[0] contains an empty reference to a Q object because it has not been
initialized with a new instance. You need to create an instance of Q and put
that into qrec[0] so that it contains an instance of Q, then you can
dereference it they way you are.

eg.
qrec[0] = new Q();

The same goes for qrec[1].
 
K

Ken Kolda

Keep in mind that allocating an array of reference-types (e.g. "new Q[2]")
just creates an array with null in each of its elements. You need to
individually allocate the elements and assign them into the array. Because
you haven't done that, the first line of Main() generates a
NullReferenceException since q[0] hasn't been initialized to an instance of
Q.

Ken
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top