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

送分小仙女□ 提交于 2019-12-13 15:25:54

问题


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";

回答1:


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...



来源:https://stackoverflow.com/questions/11493120/why-do-i-get-an-object-reference-error-with-this-multi-dimensional-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!