Why don't all paths return a value in this bool function?

Here is function:

 bool IsTaskRequirementsFulFilled()
    {
        if(taskRequirements != null)
        {
            for (int i = 0; i < taskRequirements.Length; i++)
        {
            if(!taskRequirements[i].ThereIsInInventory)
            {
               return false;
            }

            if(i == taskRequirements.Length -1)
            {
                return true;
            }
        }
        }
        else
        {
            return false;
        }
       
    }

maybe just needs extra return in case the for-loop finishes
6939910--815662--upload_2021-3-16_13-40-21.png

1 Like

Oh, that was very easy. Just put return statement outside of if statement.

Thanks, figured it out myself, I just thought that if I put return outside of the if statement, it will always return false.

This is really just personal preference, but I like to follow the “single return” rule when writing methods to avoid complications like this.

It typically starts with writing out the method body and a variable to return before anything else:

bool IsTaskRequirementsFulFilled()
{
   bool isFulfilled = false;

   return isFulfilled;
}

Then just fill in the logic in-between:

bool IsTaskRequirementsFulFilled()
{
   bool isFulfilled = false;

   if(taskRequirements != null)
   {
      for (int i = 0; i < taskRequirements.Length; i++)
      {
         if(!taskRequirements[i].ThereIsInInventory)
         {
            break;
         }

         isFulfilled = (i == taskRequirements.Length -1);
      }
   }

   return isFulfilled;
}
4 Likes

Good point, thanks