Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Not all code paths return value and unreachable code?

Hey so i have this code where i check to see if a player can remove an 'Item' from their inventory. The 'Inventory' is a Sorted Dictionary(Item, int) (subquestion: do i NEED a sorted dictionary to be able to access items in it with an index number??), and an Item is a class.

     public bool CanRemoveFromItemInventory(string item)
    {
        bool temp = false;
        if (ItemInventory.Count() <= 0)
        {
            return false;
        }
        else if (ItemInventory.Count() > 0)
        {
            for (int b = 0; b < ItemInventory.Count(); b++)
            {
                Item i = ItemInventory.Keys.ElementAt(b);
                if (i.GetName().Equals(item) && ItemInventory[i] >= 1)
                {
                    temp = true;
                }
                else
                {
                    temp = false;
                }

                if (!temp)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
        }
        else
        {
            return temp;

         }
    }
like image 949
Kartik Avatar asked Jun 27 '26 15:06

Kartik


1 Answers

The compiler doesn't attempt to understand the logic - it just applies the rules. As far as it is concerned, it is possible that the for loop executes zero times, hence the middle block is missing a return value:

    else if (ItemInventory.Count() > 0)
    {
        for (int b = 0; b < ItemInventory.Count(); b++)
        {
              // ... this always returns something
        }
        // BUT STILL NEED TO EITHER RETURN OR THROW HERE
    }

indeed, it is correct in this - as an evil malcontent could write a Count() method that returns different values each call (or to present a less evil scenario - a thread race / data mutation).

Perhaps the easiest "fix" here is to change:

    else
    {
        return temp;
    }

to simply:

    return temp;

then it will apply to all the branches.

like image 148
Marc Gravell Avatar answered Jun 29 '26 05:06

Marc Gravell