0

I have a String array object in a class, i.e, String[] particulars which I want to initialize during runtime. The same code segment worked for another class object which was not array though. Here nd is an object of class.

int i=0; foreach (DataRow row1 in dt1.Rows) { nd.particulars[i] = row1["floor"].ToString(); nd.quantity[i] = (double)row1["area"]; nd.rate[i] = (double)row1["rate"]; nd.amount[i] = (double)row1["amount"]; i++; }

The following code is throwing some NullReferenceException. The error says:

Object reference not set to an instance of an object.

The class definition is as:

class NoteDetails
 {
    public string[] particulars;
    public double[] quantity;
    public double[] rate;
    public double[] amount;

    public string[] mparticulars;
    public double[] mquantity;
    public double[] mrate;
    public double[] mamount;

    public NoteDetails()
    {
        particulars = null;
        quantity = null;
        amount = null;
        rate = null;

        mparticulars = null;
        mquantity = null;
        mamount = null;
        mrate = null;
    }
 }

Please tell me what I'm doing wrong?

Shubham Katta
  • 29
  • 1
  • 10

2 Answers2

1

You have to initialize your string array (and your others arrays too). You can do that on the constructor of the class.

nd.particulars = new string[5]; //or whatever size
NicoRiff
  • 4,803
  • 3
  • 25
  • 54
0

*NullReferenceException** seems that one of your object is null ( nd or row1 or dt1 ). If something is null do not forget to instanciate it.

You need to debug your code to check where you have this issue.

Furthermore, you should test if your object are null to avoid this error like this :

if( dt1 != null ){
 //do what you want
}

or like this (>= C#6 )

dt1?.Rows
OrcusZ
  • 3,555
  • 2
  • 31
  • 48