Reputation: 651
So I'm trying to iterate through an array of objects that all inherit from BaseClass, my code looks like this:
ChildClass object1 = new ChildClass();
OtherChildClass object2 = new OtherChildClass();
BaseClass array[] = {object1, object2}
foreach(BaseClass element in array)
{
//do stuff
}
Where obviously ChildClass and OtherChildClass inherit from BaseClass. The statement where //do stuff is gives a null reference exception every time, and sure enough when I look at the local variable assignments "element" is null... but "array" is nowhere near empty!
It seems to me that the foreach is not picking up the items in the array because they aren't exactly the base class, but I have no idea how to fix that.
Upvotes: 0
Views: 217
Reputation: 30215
Wild guess: the code you are executing is not the code you have above; the code you have above won't compile, as your array declaration needs to be:
BaseClass[] array = {object1, object2};
Give that a try, and perform a clean
or rebuild
step.
Upvotes: 1