0

I have two objects: 'Table' and 'Record'. 'Table' has a property 'Items' that is an array of type 'Record[]'.

How do I set the 'Items' property of a specific instance of 'Table' (e.g., table.Items[0]) to a specific instance of 'Record' (e.g., first_record)?

I tried to code it as follows, but my code results in a "NullReferenceException was unhandled" error.

Record first_record = new Record();
first_record.Field1 = "r1f1";
first_record.Field2 = "r1f2";
first_record.Field3 = "r1f3";

Record second_record = new Record();
second_record.Field1 = "r2f1";
second_record.Field2 = "r2f2";
second_record.Field3 = "r2f3";

Table table = new Table();
table.Items[0] = first_record;
table.Items[1] = second_record;

Thank you

exaudio
  • 36
  • 5
  • Please carefully read [MCVE] guidance to make your future questions better - in this case everyone knows that you didn't initialized array property, but in other cases lack of code that actually demonstrates the problem will likely earn you nice pile of downvotes. – Alexei Levenkov Jan 25 '17 at 03:49
  • @Abion47, I know it's clear I'm not a professional coder. But, I believe the code I provided in my question does actually demonstrate the problem. I put the corrected code in the answer I provided to my own question. – exaudio Jan 25 '17 at 04:50
  • @Abion47, I should add that in my answer I did link to a similar question that helped me figure out my own problem. While my question may be trivial to experienced coders I don't think it's an exact duplicate of other questions. – exaudio Jan 25 '17 at 04:57
  • Please read post as if it provided by some random person - you'll notice that there is no information about `Table` type (not even if it is class or struct, definitely no constructor), unrelated code for creating multiple `Record` instances with extra fields - basically no way to actually reproduce the problem. Also there is no *demonstrated* effort of author performing research on particular exception. At that point you may wonder why post did not get a lot of downvotes for lack of information and was not closed as "missing minimal code". – Alexei Levenkov Jan 25 '17 at 06:00
  • @Abion47, thank you for the feedback. – exaudio Jan 25 '17 at 06:03

1 Answers1

0

Stackoverflow suggested a similar question that provided my answer. I failed to initialize the array. Here's the line I was missing:

table.Items = new Record[2];

Inserting that line into the code from my original question results in the following:

Record first_record = new Record();
first_record.Field1 = "r1f1";
first_record.Field2 = "r1f2";
first_record.Field3 = "r1f3";

Record second_record = new Record();
second_record.Field1 = "r2f1";
second_record.Field2 = "r2f2";
second_record.Field3 = "r2f3";

Table table = new Table();
table.Items = new Record[2];
table.Items[0] = first_record;
table.Items[1] = second_record;

That did the trick. Thank you Stackoverflow!

Community
  • 1
  • 1
exaudio
  • 36
  • 5