-1

I have an object which I need to populate with some data. But when I try to populate the Party, I get a null reference error.

The object: https://pastebin.pl/view/f9f34c0e (Basically an object with 2 objects that contain an array of other objects)

Initializing:

Models.InHouse.TestSpec.InhouseOrder io = new Models.InHouse.TestSpec.InhouseOrder {
Header = new Models.InHouse.TestSpec.InhouseOrderHeader { Party = new Models.InHouse.TestSpec.InhouseOrderHeaderParty[10] },
content = new Models.InHouse.TestSpec.InhouseOrderContent { Item = new Models.InHouse.TestSpec.InhouseOrderContentItem[100] }};

But when I try to access io.header.Party[0].ID I get a Null Reference error. In the end, I will serialize it to a XML.

Jason Aller
  • 3,391
  • 28
  • 37
  • 36
NewGuy
  • 11
  • 2
  • Try : if(io.header.Party[0] == null) io.header.Party[0] = new InhouseOrderHeaderParty(); You created an array of the parties but did not construct each individual party. – jdweng Mar 26 '21 at 09:11
  • 1
    [ask], and [mre]. Question must be self containt. And all revelante code should not be hosted in 3rd party site. For null ref exception we have this big gide line https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it. And [Array Elements] part of the accepted answer address this issue – Drag and Drop Mar 26 '21 at 09:14

1 Answers1

0

Well when you initialize like:

Party = new Models.InHouse.TestSpec.InhouseOrderHeaderParty[10]

Now the Party is an array of Models.InHouse.TestSpec.InhouseOrderHeaderParty with capacity of 10, but these 10 array items has the default value of Models.InHouse.TestSpec.InhouseOrderHeaderParty which is null.

You can later do something like:

for(int i=0; i< Party.Length; i++)
    Party[i] = new Models.InHouse.TestSpec.InhouseOrderHeaderParty();

Update (Based on your comment):

You can intialize the array Items like:

Header = Enumerable.Range(1,10).Select(x => new Models.InHouse.TestSpec.InhouseOrderHeaderParty()).ToArray();
Peter Csala
  • 4,906
  • 7
  • 11
  • 29
Ashkan Mobayen Khiabani
  • 30,915
  • 26
  • 90
  • 147