0

I have had an issue with a specific scenario. I have an application that will have a Samples object that has, in addition to its own attributes, an array of another object type Axe. This object type Axe consists of N objects of type Point. Thus a Sample will have a N number of Axe's inside and each Axe will have a N number of Point's (always the same number of points). Classes are made with their certain attributes, but at the time of instantiating'm having problems. I need the code to dynamically instantiate as the number of Axe's and Point's may vary.

At the moment I have this code:

        const int SampleSize = 6;
        const int AxeSize = 6;

        Sample Samp = new Sample(SampleSize);

        for (int i = 0; i < SampleSize; i++)
        {
            Samp.AxeA[i] = new Axe(AxeSize);
        }

        for (int i = 0; i < AxeSize; i++)
        {
            DevExpress.Web.ASPxTabControl.TabPage PaG = new DevExpress.Web.ASPxTabControl.TabPage { Text = "Aba " + i };
            ASPxPageControl1.Page.Items.Add(i, PaG);

            for (int j = 0; j < AxeSize; j++)
            {
                Table X = new Table { CssClass = "datatable" };
                TableRow Rw = new TableRow();
                Label L = new Label { Text = "Linha" + j };
                Rw.Controls.Add(L);
                X.Rows.Add(Rw);
                PaG.Controls.Add(X);
            }
        }

And for the class Sample I have this constructor public Axe[] AxeA;

    public Sample(int NAxe)
    {
        Axe[] AxeA = new Axe[NAxe];

    }

For the Axe:

 public Point[] P;

    public Axe(int Npoint)
    {
        Point[] P = new Point[Npoint];

    }

On run I got a error of null reference: "Object reference not set to an instance of an object." on the first new Axe that I tryied to instance. What am I doing wrong?

Tulio VS
  • 5
  • 3

1 Answers1

0

You're declaring new local instances of your AxeA and P variables in the constructors instead of assigning values to the parent properties. Instead of this:

public class Sample {
    public Axe[] AxeA;
    public Sample(int nAxe){
        Axe[] AxeA = new Axe[nAxe]; // declaring a new local variable named AxeA which hides the parent scope variable
    }
}

You should do this:

public class Sample {
    public Axe[] AxeA;
    public Sample(int nAxe){
        AxeA = new Axe[nAxe]; // assigning to parent scope instead of declaring new variable
    }
}

Likewise for your Axe class:

public class Axe {
    public Point[] P;
    public Axe(int nPoint)
    {
        P = new Point[nPoint]; // likewise
    }
}
Rudism
  • 1,505
  • 10
  • 13