Why the null reference?

Hello, I get a null reference exception in the following code:

the variable “itemInstance” is of class Item,
soil inherits from Item.
However, when the code goes to check soil.contents[0] (a member of the inherited class) I get the error.

			if(isInitialized == false){
				soil = itemInstance as Soil;
				isInitialized = true;
			}

			if( soil.contents[0] != null ){   //<<---- NULL REFERENCE EXCEPTION HERE
				Seed seed = new Seed();
				seed = (Seed)soil.contents[0];
				soilState = SoilState.fertile;
			}

Thanks!

EDIT: I should add that itemInstance is declared as an Item but a Soil was put in to it.

There are a few possibilities that I see:

  1. itemInstance is null
  2. isInitialized is true already (so soil never gets set)
  3. Soil is not a sub-class of Item
  4. soil.contents is null instead of an array of Seeds

Also, just a quick tip, you don’t need to do:

if (isInitialized == false) { ... }

Since isInitialized is a boolean already you can just do:

if (!isInitialized) { ... }

I’m not sure when this portion of the code runs in your project, but if it checks soil.contents[0] before you set soil equal to something it’ll throw that error.

If it’s not that I think it may be something in itemInstance, perhaps your contents array isn’t being declared/populated or it just doesn’t exist.