rahularyansharma
rahularyansharma

Reputation: 10755

Why do I get an "object reference error" with this multi dimensional array?

Here is my class pax

 public class pax
    {
        public pax();

        [SoapElement(DataType = "integer")]
        public string age { get; set; }
        public string firstName { get; set; }
        public string lastName { get; set; }
        public string paxType { get; set; }
        public string title { get; set; }
    }

and i have declare the following array

pax[][]rooms=new pax[3][];

        rooms[0][0].paxType = "Adult";
        rooms[0][1].paxType="Adult";
        rooms[0][2].paxType="Child";
        rooms[0][2].age = "6";

Its throwing an error Object reference not set to an instance of an object. on line

 rooms[0][0].paxType = "Adult";

Upvotes: 2

Views: 1320

Answers (1)

Daniel Mošmondor
Daniel Mošmondor

Reputation: 19956

This will only give you array.

pax[][]rooms=new pax[3][];

To instantiate object, you have to new it:

rooms[0][0] = new pax();

You might be coming from C++ and may think that object array automatically create all objects, but that's not the case here - you will have to create each one because it is null before you do it.

EDIT:

Since you have jagged array here:

pax[][]rooms=new pax[3][];
rooms[0]=new pax[3];
rooms[0][0]=new pax();

Jagged array = array of arrays. If you need multidimensional (2-dimensional array), that's different story, and you would say:

pax[,] rooms=new pax[3,3];

for example...

Upvotes: 4

Related Questions