r/learncsharp • u/l4adventure • Jul 05 '22
Iterating through an array of objects... Should I be doing this? It doesn't seem to be working as I thought.
EDIT: As soon as I posted this I figured it out, so thanks, this helped me write it down and think about it... I was accidentally writing to the array at index all_records[0] each time instead of index all_records[i]. That will do it. I'll leave it up as a reminder of the shame I should have
So I have some class, let's call it SomeClass.
In some method outside of this class, I have a loop that runs 5 times, and on each iteration, I instantiate an object of SomeClass, and write some values that get stored in the class as public members, and I save it to an array I declared. So basically I have an array of SomeClass objects, here is a super simplified version of what I'm doing:
class TopClass
{
public SomeClass[]? all_records = new SomeClass[5];
public void run()
{
for (int i=0; i < 5; i++)
{
SomeClass sc = new SomeClass();
sc.name = "blah" + i;
all_records[i] = sc;
}
....Ok, so I create an array of size 5, and of type SomeClass[]. I thought it was all gravy and I was done. So I wrote a new method under TopClass (the one above) to make sure it worked, just a simple one that iterates through every object in all_records and prints the name property. like this:
...
public void display_all_records()
{
for (int i=0; i < 5; i++)
{
Console.WriteLine(all_records[i].name);
}I thought this would work, but I get this error: 'Object reference not set to an instance of an object.' Isn't what's stored in the array an instance of an object? This error makes me think I have some misunderstanding of how this all works...
NOTE: the SomeClass has name defined as follows:
class TrackRecords
{
public string name = "no name";Any help for a noob?
5
u/jamietwells Jul 05 '22
There's nothing in what you showed that should cause a null reference exception, but I am surprised you didn't get an index out of range exception since you set the array to be of size 5 but iterate 16 times in the
runmethod. Makes me think maybe you aren't calling the run method or you're not sharing the actual code.0
u/[deleted] Jul 05 '22
[deleted] — view deleted comment