Not all code paths return a value?

Hello,

This is probably an easy one, but I’m not a very experienced programmer. I understand what the error “Not all code paths return a value” means, but I don’t know why I would get it in this case.

I’m creating an inventory system for an RPG from scratch, I have the following function to look for a null space in the inventory array, if it is null, put Item in it. The function will then return a string “Added Item” or “Inventory full.” What’s wrong here?

        	public string AddItem(Item addedItem){
        		for(int i = 0; i < baseInvSize; i++){
        			if(playerInventory *== null){*

_ playerInventory = addedItem;_
* return “added”;*
* }*
* else*
* return “Inventory Full”;*
* }*
}

First, you are really only checking the first item in the array with the way you’ve structured your if statement.

Second of all, as baseInvSize is a variable, it’s entirely possible for your loop to never be entered.

So really, you want to loop through the array and if you find a null position, add the item and return added (I’d also use a boolean, but that’s irrelevant at this point). If you get through the entire loop and nothing is found, then you return Inventory Full.

So:

public string AddItem(Item addedItem){
    for(int i = 0; i < baseInvSize; i++){
        if(playerInventory *== null){*

playerInventory = addedItem;
return “added”;
}
}
return “Inventory Full”;
}