Reputation: 27
I have a situation where I have defined a class within a class, resembling the following:
public partial class ProdData
{
private string prodID;
private string Description;
...and so on until I get to
private ProdDataChildren[] childItemsField;
}
ProdDataChildren is it's own class, which I am using to identify sub-products that may belong to the parent product, hence the array.
In the main part of my program I have a loop that reads in records, sort of like:
while (myReader.Read())
{
ProdData ProductDataIn = new ProdData();
ProductDataIn.ID = "values assigned here";
until I get to the point there I want to assign a child, this is where I am getting the error "Object reference not set to an instance of an object", using the following statement
ProductDataIn.ChildItems[i].ProdID = "string variable here";
}
I beleive the cause of the error is something to do with the current ChildItems being set to null, but how am I supposed to assign a value to it? Do I need to instantiate and instance of the child item somehow and how would I do this?
Any help would be appreciated, I realize this might be a no brainer for some.
Upvotes: 0
Views: 860
Reputation: 3397
You only declared the variable. You didn't create a new instance of the array so you are trying to access an object that hasn't yet been created.
Upvotes: 1
Reputation: 125630
First of all, you have to initialize your field before assigning anything to that collection. I would suggest using List
instead of Array
:
public partial class ProdData
{
...and so on until I get to
private List<ProdDataChildren> childItemsField = new List<ProdDataChildren>();
}
With List
you'll be able to do following:
ProductDataIn.ChildItems.Add(new ProdDataChildren() { ProdID = "string variable here" });
Upvotes: 2